Sorting an array of objects by arbitrary list in JavaScript

Given an array of such objects:

objects = [
  { id: 'aaaa', description: 'foo' },
  { id: 'bbbb', description: 'bar' },
  { id: 'cccc', description: 'baz' }
];

And an array of these lines:

order = [ 'bbbb', 'aaaa', 'cccc' ];

How do I sort the first array so that the id attribute matches the order of the second array?

+3
source share
2 answers

Try the following:

objects.sort(function(a, b){
    return order.indexOf(a.id) - order.indexOf(b.id)
});

Assuming the variables are similar to the way you declared them in the question, this should return:

[
    { id: 'bbbb', description: 'bar' },
    { id: 'aaaa', description: 'foo' },
    { id: 'cccc', description: 'baz' }
];

(It actually changes the variable objects)

+12
source

You need a way to translate a string to a position in an array, i.e. index functions for an array.

There is one in new browsers, but for backward compatibility you need to add it if it is not there:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(str) {
    var i;
    for (i = 0; i < this.length; i++) if (this[i] == str) return i;
    return -1;
  }
}

Now you can sort the array by turning the string into an index:

objects.sort(function(x,y){ return order.indexOf(x.id) - order.indexOf(y.id); });

: http://jsfiddle.net/Guffa/u3CQW/

+1

All Articles