繁体   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