Search code examples
javascriptsorting

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

Solution

  • 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/