在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}]

因此,基本上,它必须根据MainArray标签进行排序,而且如果该标签在array1中不存在,它应该在值为0 的同一索引上附加相同的标签

您可以在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; }

您需要映射到所需的数据集,然后对映射的数据集进行排序。下面是一个例子。希望能有所帮助!

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

相关内容

最新更新