Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by arbitrary list in JavaScript

Given an array of objects like this:

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

And an array of strings like this:

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

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

like image 817
aaronrussell Avatar asked Feb 04 '14 11:02

aaronrussell


Video Answer


2 Answers

Try this:

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

Assuming the variables are like you declared them in the question, this should return:

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

(It actually modifies the objects variable)

like image 152
Cerbrus Avatar answered Sep 19 '22 14:09

Cerbrus


You need a way to translate the string into the position in the array, i.e. an index-of function for an array.

There is one in newer browsers, but to be backwards compatible you need to add it if it's 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); });

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

like image 32
Guffa Avatar answered Sep 20 '22 14:09

Guffa