Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  102] [ 4]  / answers: 1 / hits: 142423  / 13 Years ago, thu, november 17, 2011, 12:00:00

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}
];

More From » sorting

 Answers
8

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/


[#89054] Wednesday, November 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
tylerdamiena questions
;