开发者

javascript - sort by the order of a second array

开发者 https://www.devze.com 2023-01-11 03:39 出处:网络
Given: var a1 = [{name:\'Scott\'}, {name:\'John\'}, {name:\'Albert\'}]; var sortOrder开发者_高级运维 = [\'John\', \'Scott\', \'Albert\'];

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消