2017-10-19 5 views
0

に順序として考えると、別の配列プロパティによってアレイを配置し、私はここ2、配列のはjavascriptの

第一の配列は、メインデータと、それは第一配列データ注文の拠点である必要がありますプロパティによって 第二配列ですしています。

2アレイサンプル:

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

第1データアレイ

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]' }, 
] 

期待される出力が..それがなければならない第2の配列タグ順序に

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 assortorderのタグのインデックスを取ることができます。

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