2017-10-19 82 views
0

我这里有2阵列的安排给出另一个数组属性数组中的JavaScript

1阵列的主要数据,并通过 财产2个数组它必须是第一个阵列数据订单的基础秩序。

第二阵列样品:

var order_basis = [ 
{ tag:'vip' }, { tag:'home' } { tag:'work' } 
] 

第一阵列数据

var main_data = [ 
{ tag:'work',name:'sample',contact:'0987654',email:'[email protected]' }, 
{ tag:'home',name:'sample',contact:'0987654',email:'[email protected]' }, 
{ tag:'home',name:'sample',contact:'0987654',email:'[email protected]' }, 
{ tag:'work',name:'sample',contact:'0987654',email:'[email protected]' }, 
{ tag:'vip',name:'sample',contact:'0987654',email:'[email protected]' }, 
] 

期望输出是第二阵列标记顺序它必须是

基..

ReOrder(main_data ,order_basis){ 

//main code 

    return 
} 

结果是

tag:'vip' name:'sample' contact:'0987654' email:'[email protected]' 
tag:'home' name:'sample' contact:'0987654' email:'[email protected]' 
tag:'home' name:'sample' contact:'0987654' email:'[email protected]' 
tag:'work' name:'sample' contact:'0987654' email:'[email protected]' 
tag:'work' name:'sample' contact:'0987654' email:'[email protected]' 

谢谢你帮助队友! ..

回答

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: '[email protected]' }, { tag: 'home', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'home', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'work', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'vip', name: 'sample', contact: '0987654', email: '[email protected]' }]; 
 

 

 
console.log(getFormatted(main_data, order_basis));
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

通过使用带有此数据的对象,可以获取order_basis分类器标签的索引。

var order_basis = [{ tag: 'vip' }, { tag: 'home' }, { tag: 'work' }], 
 
    main_data = [{ tag: 'work', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'home', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'home', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'work', name: 'sample', contact: '0987654', email: '[email protected]' }, { tag: 'vip', name: 'sample', contact: '0987654', email: '[email protected]' }], 
 
    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; }

相关问题