相对于JavaScript中的第一个数组对第二个数组进行排序

时间:2020-04-18 14:16:37

标签: javascript arrays typescript sorting ecmascript-6

例如,我的

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 Label进行排序,并且如果该标签在array1中不存在,则应在相同索引上附加值为0的相同标签

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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; }