Sort array of objects by arbitrary list in JavaScript

arrays, javascript, sorting

Solution

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)

Problem

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?

Original source