繁体   English   中英

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

[英]Sort array of object based on another array

所以说我有一个数组:

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

而且我希望根据names属性对其进行排序,因此顺序类似于此数组:

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

最有效的方法是什么?

试试这个方法:

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);

您可以使用原始名称索引的增量。

 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; } 

简单的方法:将大块转换为一个对象,以便仅用键即可得到正确的块,然后映射到(已排序的)数组以将对象插入到位。

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