有什么办法可以解决这个问题,而不必同时连接这两个数组?

时间:2020-07-14 19:32:09

标签: javascript

我需要获取ExpectedOutput数组,该数组由数量更大的对象组成。此代码合并两个数组,然后减少更大的数量。我正在寻找一种更好的方法来做到这一点,而不必担心。预先感谢。

let arr1 = [{name: 'Almendras', amount: 0},{name: 'Nueces', amount: 0}, {name: 'Chocolate', amount: 0}];
let arr2 = [{name: 'Almendras', amount: 2}];

let expectedOutput = [{name: 'Almendras', amount: 2}, {name: 'Nueces', amount: 0}, {name: 'Chocolate', amount: 0}];

let concat = arr1.concat(arr2);

const output = Object.values(concat.reduce((x, y) => {
  x[y.name] = x[y.name] && x[y.name].amount > y.amount ? x[y.amount] : y
  return x
}, {}));

console.log(output);

1 个答案:

答案 0 :(得分:4)

您可以通过在两个阵列上分别运行concat来避免进行reduce调用:

let arr1 = [{name: 'Almendras', amount: 0},{name: 'Nueces', amount: 0}, {name: 'Chocolate', amount: 0}];
let arr2 = [{name: 'Almendras', amount: 2}];

function mergeHigher(acc, el) {
  const old = acc[el.name];
  if (!old || el.amount >= old.amount) acc[el.name] = el;
  return acc;
}

const out1 = arr1.reduce(mergeHigher, {});
const out2 = arr2.reduce(mergeHigher, out1);

console.log(Object.values(out2));