Sort an Array of Objects by Property Using sort(fn)

By  on  

Believe it or not, there's more to JavaScript than the helper methods and classes they provide your JavaScript library. No, like seriously bro; these JavaScript-given methods do exist. One of those methods, sort, is provided to every Array instance via its prototype. I've used this method once or twice in the history of ever, bro, since I make every effort to ensure proper sort on the server side, but sometimes you may receive a JSON dump and need to sort on the client side.

Most people would assume that sort would take no method and simply sort the basic items within the array:

[1, 3, 9, 2].sort();
	// Returns: [1, 2, 3, 9]
	
[1, "a", function(){}, {}, 12, "c"].sort();
	// Returns: [1, 12, Object, "a", "c", function (){}]

But nay, broseph! If you provide a function expression to the sort method, you can sort objects within the array using simple logic. Let's say you have an array of objects representing persons and you want to sort them by age. Oh yes, it can be done, and quite easily:

[
	{ name: "Robin Van Persie", age: 28 },
	{ name: "Theo Walcott", age: 22 },
	{ name: "Bacary Sagna", age: 26  }
].sort(function(obj1, obj2) {
	// Ascending: first age less than the previous
	return obj1.age - obj2.age;
});
	// Returns:  
	// [
	//	  { name: "Theo Walcott", age: 22 },
	//	  { name: "Bacary Sagna", age: 26  },
	//	  { name: "Robin Van Persie", age: 28 }
	// ]
	

The anonymous function returns whether or not the first object's age is less than the second's, thus sorting the entire array in ascending order by age. Reverse the first and second arguments to sort in descending order.

So brochacho, now you know how to sort an array of objects using JavaScript. Get to it!

Recent Features

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Translate Content with the Google Translate API and JavaScript

    Note:  For this tutorial, I'm using version1 of the Google Translate API.  A newer REST-based version is available. In an ideal world, all websites would have a feature that allowed the user to translate a website into their native language (or even more ideally, translation would be...

  • By
    Sexy Album Art with MooTools or jQuery

    The way that album information displays is usually insanely boring. Music is supposed to be fun and moving, right? Luckily MooTools and jQuery allow us to communicate that creativity on the web. The XHTML A few structure DIVs and the album information. The CSS The CSS...

Discussion

  1. Boger

    Nice read, never thought to sort objects this way. but man broseph and brochacho got me laugh to death :D

  2. champi

    Great ! how could I do this in PHP ?

  3. A little bit late, but it still may be useful… ;)

    In PHP, it is almost the same. Here is the equivalent code:

    $people = array(
      array('name' => 'Robin Van Persie', 'age' => 28),
      array('name' => 'Theo Walcott', 'age' => 22),
      array('name' => 'Bacary Sagna', 'age' => 26)
    );
    
    usort($people, function($a, $b) {
      return $a['age'] - $b['age'];
    });
    
    var_dump($people);
    

    More informations: http://php.net/manual/fr/function.usort.php

  4. Anil Gautam

    Hey I am tring your code but its not working.

  5. mauro

    hi, i have tryed to bud a sort function by attributes a lot really, and finally i find this blog, your code work for me if the attribute is a number not if it is a string, why? i have to do something in that case? really thank you

  6. Do Jo

    What if I wanted to sort by “name”?

  7. Fahad Rafiq

    Array sorting is very important when we deal with many array elements. We have variety of array functions which can sort arrays with respect to value as well as with respect to key. Explore the most important array sorting functions in PHP here: http://www.cloudways.com/blog/php-arrays-sorting-functions/.

  8. Why do you do

    return obj1.age - obj2.age;

    and not

    return obj1.age > obj2.age;

    .. and most importantly why do these two things give the same result?:)

  9. Lumberjack

    Sorry but it seems the parser screwed up my message. Let me try again:

    return a.age - b.age;

    The above will return -1 if a is less than b.
    If a is equal to b, then it will return 0.
    If a is greater than b, then it will return 1.

    return a.age > b.age;

    This however will return a binary.
    If a is greater than b, then it will return true.
    In all other cases where a is equal to b OR a is less than b, it will return false.

    This will give an incorrect result for the case where a is less than b.

    Hopefully that makes sense.

  10. Jay

    Hi When I sort the below array of objects by its x.

    [ { x: 0, s: '-' },
      { x: 6, s: '-' },
      { x: 0, s: '-' },
      { x: 6, s: '-' },
      { x: 4, s: '-' },
      { x: 0, s: '-' },
      { x: 6, s: '-' },
      { x: 0, s: '-' },
      { x: 6, s: '-' },
      { x: 0, s: '-' },
      { x: 4, s: 'that' },
      { x: 3, s: 'be' },
      { x: 0, s: 'to' },
      { x: 1, s: 'be' },
      { x: 5, s: 'question' },
      { x: 1, s: 'or' },
      { x: 2, s: 'not' },
      { x: 4, s: 'is' },
      { x: 2, s: 'to' },
      { x: 4, s: 'the' } ]
    
    this is what I get
    
    [ { x: 0, s: '-' },
      { x: 0, s: 'to' },
      { x: 0, s: '-' },
      { x: 0, s: '-' },
      { x: 0, s: '-' },
      { x: 0, s: '-' },
      { x: 1, s: 'be' },
      { x: 1, s: 'or' },
      { x: 2, s: 'to' },
      { x: 2, s: 'not' },
      { x: 3, s: 'be' },
      { x: 4, s: 'the' },
      { x: 4, s: 'is' },
      { x: 4, s: '-' },
      { x: 4, s: 'that' },
      { x: 5, s: 'question' },
      { x: 6, s: '-' },
      { x: 6, s: '-' },
      { x: 6, s: '-' },
      { x: 6, s: '-' } ]
    

    If you check its getting sorted in ascending order but its changing my input order, if you see the object at index[1] should have been placed at index[5] on basis how the array input is so can any one let me know how do we achieve that.

    This is my code

    m = m.sort(function(a,b){return a.x - b.x});
       console.log(m);
  11. Eddie Ebeling

    Good stuff, brah! Saved me 5 more Google searches!

  12. Here is one that is pretty funky, it sorts by time, when time is a string:

    newAddEvents.sort((a, b) => (Date.parse('1970-01-01T' + a.time) > Date.parse('1970-01-01T' + b.time)) ? 1 : -1);
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!