Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple function to sort an array of objects

I would like to create a (non-anonymous) function that sorts an array of objects alphabetically by the key name. I only code straight-out JavaScript so frameworks don't help me in the least.

var people = [     {'name': 'a75', 'item1': false, 'item2': false},     {'name': 'z32', 'item1': true,  'item2': false},     {'name': 'e77', 'item1': false, 'item2': false} ]; 
like image 303
John Avatar asked Nov 17 '11 22:11

John


People also ask

How do you sort and array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array in a function?

JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.


2 Answers

How about this?

var people = [ {     name: 'a75',     item1: false,     item2: false }, {     name: 'z32',     item1: true,     item2: false }, {     name: 'e77',     item1: false,     item2: false }];  function sort_by_key(array, key) {  return array.sort(function(a, b)  {   var x = a[key]; var y = b[key];   return ((x < y) ? -1 : ((x > y) ? 1 : 0));  }); }  people = sort_by_key(people, 'name'); 

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

like image 186
David Brainer Avatar answered Oct 06 '22 07:10

David Brainer


You can sort an array ([...]) with the .sort function:

var people = [     {'name': 'a75', 'item1': false, 'item2': false},     {'name': 'z32', 'item1': true,  'item2': false},     {'name': 'e77', 'item1': false, 'item2': false}, ];  var sorted = people.sort(function IHaveAName(a, b) { // non-anonymous as you ordered...     return b.name < a.name ?  1 // if b should come earlier, push a to end          : b.name > a.name ? -1 // if b should come later, push a to begin          : 0;                   // a and b are equal }); 
like image 43
pimvdb Avatar answered Oct 06 '22 08:10

pimvdb