Treehouse

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!

ydkjs-5.png

Recent Features

  • Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images...

Incredible Demos

  • Fix Anchor URLs Using MooTools 1.2

    The administrative control panel I build for my customers features FCKEditor, a powerful WYSIWYG editor that allows the customer to add links, bold text, create ordered lists, and so on. I provide training and documentation to the customers but many times they simply forget to...

  • Fancy Navigation with MooTools JavaScript

    Navigation menus are traditionally boring, right? Most of the time the navigation menu consists of some imagery with a corresponding mouseover image. Where's the originality? I've created a fancy navigation menu that highlights navigation items and creates a chain effect. The XHTML Just some simple...

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

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