我这里有2个数组
第一个数组是主要数据和 第二个数组属性,它必须是第一个数组数据顺序的基础。
第二个数组样本:
var order_basis = [
{ tag:'vip' }, { tag:'home' } { tag:'work' }
]
第一个数组数据
var main_data = [
{ tag:'work',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'home',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'home',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'work',name:'sample',contact:'0987654',email:'sample@email.com' },
{ tag:'vip',name:'sample',contact:'0987654',email:'sample@email.com' },
]
预期产出
基于第二个数组标记顺序,它必须是..
ReOrder( main_data ,order_basis ){
//main code
return
}
结果是
tag:'vip' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'home' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'home' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'work' name:'sample' contact:'0987654' email:'sample@email.com'
tag:'work' name:'sample' contact:'0987654' email:'sample@email.com'
感谢您帮助配偶! ..
答案 0 :(得分:1)
您可以使用包含此数据的对象来获取order_basis
assortorder标记的索引。
var order_basis = [{ tag: 'vip' }, { tag: 'home' }, { tag: 'work' }],
main_data = [{ tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'vip', name: 'sample', contact: '0987654', email: 'sample@email.com' }],
order = {};
order_basis.forEach(function (o, i) { order[o.tag] = i + 1 });
main_data.sort(function (a, b) {
return order[a.tag] - order[b.tag];
});
console.log(main_data);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
您可以根据order_basis
数组对主函数进行排序。
function getFormatted(main, order_basis){
order_basis = order_basis.map(x => x.tag);
return main.sort(function(a, b){
if(order_basis.indexOf(a.tag) > order_basis.indexOf(b.tag))
return 1;
return -1;
});
}
var order_basis = [{ tag: 'vip' }, { tag: 'home' }, { tag: 'work' }],
main_data = [{ tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'home', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'work', name: 'sample', contact: '0987654', email: 'sample@email.com' }, { tag: 'vip', name: 'sample', contact: '0987654', email: 'sample@email.com' }];
console.log(getFormatted(main_data, order_basis));
.as-console-wrapper { max-height: 100% !important; top: 0; }