我需要获取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);
答案 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));