1

How can I sort an array containing objects by some property, e.g., name?

For example:

 var cart = [
     {'name': 'nokie', 'description': ''},
     {'name': 'htc', 'description': 'this is htc phone' },
     {'name': 'samsung', 'description': ''}
];

should be sorted to:

 var cart = [  
     {'name': 'htc', 'description': 'this is htc phone' },
     {'name': 'nokie', 'description': ''},
     {'name': 'samsung', 'description': ''}
];
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100

2 Answers2

2

You can use javascript built in function sort

example:

cart.sort(function(a, b){return a.name > b.name})

This will sort it by name. It is actually Array built in function. I You have just numbers You do not have to put function inside but for arrays of objects You should. Inside of function You can make Your own compare rules.

chriss
  • 669
  • 4
  • 9
2

All you need is to compare name property with localeCompare method:

cart.sort(function(a, b) {
    return b.name.localeCompare(a.name);
});
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • When editing the OP I assumed they wanted to sort by `name`. Sorting by description would be just as valid given the example. Either way, it's a minor difference. – Ingo Bürk Oct 24 '14 at 08:17