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} ];
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
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.
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/
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With