大家好,我有一个任务要做。这是交易: 我有一个数组
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) => {
//... ?
}
答案 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);