0

for example

myArr= [
    {name:"Joe",  id:3,  date: "2012.10.12"},
    {name:"Ed",   id:43, date: "2012.02.12"},
    {name:"Mark", id:22, date: "2012.02.11"}
];

so how can I sort this Array by date?

This is just small example, but it will be like 1000 Objects inside that Array. I have searched on the Internet and found some examples that used the sort() function but it doesn't work in my big Array.

3
  • 1
    So what is the code you used that is not working to sort it? Sorting large arrays can lead to slowness. We can not help you unless you show what you did that causes the slowness. Commented Jan 6, 2017 at 13:17
  • As hinted by epascarello, if you don't show what you have tried, we won't know where you went wrong, we can only solve the problem for you, which is not the intention of stack overflow. stackoverflow.com/help/how-to-ask Commented Jan 6, 2017 at 13:21
  • is not the same question !!! as Commented Jan 6, 2017 at 14:08

1 Answer 1

5

Assuming the dates are just strings formatted as in your code, you can do this:

myArr.sort( (a,b) => a.date.localeCompare(b.date) )

The sort method takes as a parameter a function that will be called every time it needs to compare two elements of the array. So to sort by a particular field, you pass a function that compares those fields of the two objects passed in.

The sort comparator function has to return a special value indicating the correct order: -1 if the first parameter (conventionally called a) should come before the second (b); 1 if b should come before a; or 0 if they're equal (so the order doesn't matter). Fortunately, there's already a method that compares strings and returns the proper value for sort (if you call it on a and pass b as a parameter): localeCompare. Since the fields you're comparing are strings, you can just call that on the fields in your comparison function to return the proper value for the sort.

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

1 Comment

Omg you are my savior !! Thank you very much!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.