简体   繁体   English

根据另一个数组对对象数组进行排序

[英]Sort array of object based on another array

So let's say I have an array: 所以说我有一个数组:

const chunks = [
    {id: 0, names: ['app']}, 
    {id: 1, names: ['contact']}, 
    {id: 2, names: ['bootstrap']}
];

And I want it to be sorted based on the names property, so the order is like in this array: 而且我希望根据names属性对其进行排序,因此顺序类似于此数组:

const original = ['bootstrap', 'app', 'contact'];

What is the most efficient way to do this? 最有效的方法是什么?

Try this method: 试试这个方法:

const chunks = [{id: 0, names: ['app']}, {id: 1, names: ['contact']}, {id: 2, names: ['bootstrap']}];
const original = ['bootstrap', 'app', 'contact'];
let result = [];
for(let i = 0; i < original.length; i++) {
    for(let j = 0; j < chunks.length; j++) {
        if(chunks[j].names.indexOf(original[i]) !== -1) {
            result.push(chunks[j]);
        }
    }
}
console.log(result);

You could use the delta of the indices of names in original. 您可以使用原始名称索引的增量。

 const chunks = [{ id: 0, names: ['app'] }, { id: 1, names: ['contact'] }, { id: 2, names: ['bootstrap'] }], original = ['bootstrap', 'app', 'contact']; chunks.sort((a, b) => original.indexOf(a.names[0]) - original.indexOf(b.names[0])); console.log(chunks); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Easy way: convert chunks into an object so you get the correct one with just the key, then map over the (already sorted) array to plug in the object in place. 简单的方法:将大块转换为一个对象,以便仅用键即可得到正确的块,然后映射到(已排序的)数组以将对象插入到位。

cMap = chunks.reduce((p,c) => Object.assign( p, {[c.names[0]]: c} ), {});
const sorted = original.map(k => cMap[k]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM