簡體   English   中英

相對於 javascript 中的第一個數組對第二個數組進行排序

[英]Sorting second array with respect to first array in javascript

例如我的

Mainarray = [{label:a,value:5} ,
{label :b , value :4 },
{label :c , value :10},
{label :d , value :5}]

我要排序的數組是

array1 = [ {label :c ,value 5},{label :a ,value:2}

array1 排序后必須是這樣的

sortedarray= [{label:a,value :2} ,
{label :b , value :0 },
{label :c , value :5},
{label :d , value :0}]

so basically, it must be sorted with respect to MainArray Label, and also if that label doesnt exist in array1, it should append the same label on same index with value 0

您需要將 map 轉換為您想要的數據集,然后對映射的數據集進行排序。 這是一個例子。 希望有幫助!

 const array = [ { label: 'c', value: 5 }, { label: 'b', value: 4 }, { label: 'a', value: 10 }, { label: 'd', value: 5 } ] const toSort = [ { label: 'b', value: 1 }, { label: 'a', value: 5 }, { label: 'c', value: 2 } ]; const mapToSort = array.map(_ => { const item = toSort.find(x => x.label === _.label); return item || { label: _.label, value: 0 }; }) const getIndex = item => array.findIndex(_ => _.label === item.label); const sorted = mapToSort.sort((a, b) => getIndex(a) - getIndex(b)); console.log(JSON.stringify(sorted));

您可以在Map和 map 使用新值或零的數據數組中收集新值。

 var data = [{ label: 'a', value: 5 }, { label: 'b', value: 4 }, { label: 'c', value: 10 }, { label: 'd', value: 5 }], array = [{ label: 'c', value: 5 }, { label: 'a', value: 2 }], values = new Map(array.map(({ label, value }) => [label, value])), result = data.map(({ label }) => ({ label, value: values.get(label) || 0 })); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM