1

If I have an array of objects with properties and I wanted to sort the objects by a specific property, how would I be able to do this? For example, let's say that I had a bunch of news objects each with a date property.

How would I be able to sort each of the objects in javascript by date?

1
  • This has been asked many, many times before. Commented Aug 4, 2011 at 6:54

3 Answers 3

3

If your array is arr:

arr.sort(function(a,b) { 
    return ( a.date < b.date ? -1 : (a.date > b.date ? 1 : 0 ) );
});
Sign up to request clarification or add additional context in comments.

2 Comments

sorry do you mean date instead of data?
are these outer parenthesis really needed?
0

You need to pass your own function to .sort(), something like this:

someArray.sort(function(a, b) {
  if (a.date < b.date)
    return -1;
  else if (a.date > b.date)
    return 1;
  return 0;
});

Your function just needs to be able to compare any two given objects and return negative or positive depending on which comes first or zero if they're equal. The .sort() function will take care of the rest.

This means you can sort on whatever property of the object you like, and even (optionally) introduce a secondary sort for cases where the first property is equal. You can also control ascending versus descending just by negating your return values.

1 Comment

Oops, probably should pay more attention to that banner at the top telling me another answer was posted. Oh well, I shall defiantly leave my answer up too since I gave a brief explanation along with the code.
0

You can supply a sort function to the Array's sort method:

// Sample data
var newsArray = [
   {date: '2010/8/12'},
   {date: '2012/8/10'},
   {date: '2011/8/19'}
 ];

// Sorting function
function sortNewsArray(arr) {
  return arr.sort(function(a, b) {
      return new Date(a.date) - new Date(b.date);
    }
  );
}

Provided the date strings can be converted to dates that simply. If not, just reformat so that they can, either in the data or the sort function.

Original order:

  1. 2010/8/12
  2. 2012/8/10
  3. 2011/8/19

Sorted order:

  1. 2010/8/12
  2. 2011/8/19
  3. 2012/8/10

Comments

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.