Scott Klarenbach
Scott Klarenbach

Reputation: 38721

javascript - sort by the order of a second array

Given:

var a1 = [{name:'Scott'}, {name:'John'}, {name:'Albert'}];
var sortOrder = ['John', 'Scott', 'Albert'];

How can I sort the first array (by property) based on the order specified in the second array.

// result: [{name:'John'}, {name:'Scott'}, {name:'Albert'}]

Thanks.

Upvotes: 2

Views: 1403

Answers (1)

sje397
sje397

Reputation: 41812

a1.sort(function(a,b) {
  return (
    sortOrder.indexOf(a.name) < sortOrder.indexOf(b.name) ? -1 : 1
  );
});

Upvotes: 7

Related Questions