根据列表顺序对对象数组进行排序

时间:2018-06-29 13:58:17

标签: javascript arrays sorting object

大家好,我有一个任务要做。这是交易: 我有一个数组

arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}]

和排序顺序列表sortSequence = ['dad','mom','bro'] 因此,根据此列表,我需要一个输出数组等于

arr = [{role:'dad', name:'d'}, {role:'mom', name:'a'}, {role:'bro', name: 'c'}]

如何使用sort方法做到这一点?

const sortAccordingList = (list, arr) => {
    //... ?
}

1 个答案:

答案 0 :(得分:2)

您可以使用indexOf获取角色的索引

var sortSequence = ['dad', 'mom', 'bro'];
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];

arr.sort((a, b) => sortSequence.indexOf(a.role) - sortSequence.indexOf(b.role));

console.log(arr);


您还可以将sortSequence作为对象。这将使获取排序顺序更加容易。喜欢:

var sortSequence = {dad:1,mom:2,bro:3};
var arr = [{role:'mom', name:'a'}, {role:'dad', name:'d'}, {role:'bro', name: 'c'}];

arr.sort((a, b) => sortSequence[a.role] - sortSequence[b.role]);

console.log(arr);