如何基于其他数组JS对数组进行排序

时间:2020-08-31 21:17:19

标签: javascript sorting

一个或多个数组

var items = [
    ['alice','bob', 'emma', 'isabella'],
    ['emma','sofia', 'alice', 'bob'],
    ['bob','emma', 'alice']
];

如何按照具体顺序['alice','emma','bob', ..other]映射项目

每个数组都可以包含alice, bob and emma等项目

1 个答案:

答案 0 :(得分:1)

var items = [
    ['alice','bob', 'emma', 'isabella'],
    ['emma','sofia', 'alice', 'bob'],
    ['bob','emma', 'alice']
];

const NAME =  ['alice','bob', 'emma'];
let res = [];

items.forEach(names => {
    names.sort((a,b) => {
        indA = NAME.indexOf(a);
        indB = NAME.indexOf(b);
        if (indA!=-1)
            return (indB!=-1) ? indA-indB : -1;
        else return (indB!=-1) ? 1 : 0;
    });
    res.push(names);
});

console.log(res);