0

Have a large list of array data of which can exceed to N number. Need to sort the array elements with latest date and time. enter image description here

let array = [{"name": "Apple","modified_date": "2020-08-26 02:03:23.756"},
             {"name": "Orange","modified_date": "2020-08-26 03:03:23.756"},
             {"name": "Grapes","modified_date": "2020-08-26 04:03:23.756"}................N number length]

able to sort using small size of array

let sort = array.sort(function(a, b) { 
            return (new Date(b.modified_date)).getTime() - (new Date(a.modified_date)).getTime();
        });

But with large length array correct sorting is not happening.What could be the issue!!!!?

7
  • What do you mean by "sorting is not happening"? Commented Aug 26, 2020 at 8:50
  • Plus 542 is not that big to be honest, you might get a bit of a freeze when tackling 1m+ entries, in which case you could proceed within a web worker (it won't reduce the sorting time, but will allow the UI not to freeze). Commented Aug 26, 2020 at 8:52
  • @Nick I mean correct sorting is not happening among the all N elements of array. Commented Aug 26, 2020 at 8:52
  • 1
    @New123 Probably the specific input is needed.. Commented Aug 26, 2020 at 8:57
  • 1
    I posted and answer, but it would have helped only if your sort function did not finish (as opposed to it not sorting correctly). There is no need to create Date() object. String compare should give you the same result here. Commented Aug 26, 2020 at 9:00

1 Answer 1

2

You could avoid creation of O(2*n*log(n)) Date objects. String compare will yield the same result as Date(str).getTime() compare yields. The string comparison method is a very much better idea.

let array = [{"name": "Apple","modified_date": "2020-08-26 02:03:23.756"},
             {"name": "Orange","modified_date": "2020-08-26 03:03:23.756"},
             {"name": "Grapes","modified_date": "2020-08-26 04:03:23.756"}];

array.sort((a, b) => b.modified_date.localeCompare(a.modified_date));
console.log(array);

Sign up to request clarification or add additional context in comments.

1 Comment

Actually the results will be different since in some browsers new Date("2020-08-26 02:03:23.756").getTime() returns NaN. The string comparison method is a very much better idea. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.