我有两个数组对象(arrayList1,arrayList2),现在我想把这两个数组合并成一个数组对象。
以下是我使用的条件:
- 根据键名type将两个数组合并为一个数组。
- arrayList2的值将覆盖arrayList1的值。
- 我得到了预期的输出,但我担心效率和性能。
请有经验的人简化我的代码。
注意:
- 最好使用Array.reduce函数而不使用任何插件/库。
- 我添加了示例输入以便理解。元素的顺序将更改,两个数组的大小也会更改。
Translated content:
我有两个数组对象(arrayList1,arrayList2),现在我想把这两个数组合并成一个数组对象。
以下是我使用的条件:
- 根据键名type将两个数组合并为一个数组。
- arrayList2的值将覆盖arrayList1的值。
- 我得到了预期的输出,但我担心效率和性能。
请问有没有更高效和性能更好的方法来简化我的代码?
注意:
- 最好使用Array.reduce函数而不使用任何插件/库。
- 我添加了示例输入以便理解。元素的顺序将更改,两个数组的大小也会更改。
const arrayList1 = [
{ type: "A", any: 11, other: "ab", props: "1" },
{ type: "B", any: 22, other: "bc", props: "2" }, // same type
{ type: "C", any: 33, other: "df", props: "3" }
];
const arrayList2 = [
{ type: "D", any: 44, other: "aa", props: "11" },
{ type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
{ type: "E", any: 44, other: "cc", props: "33" }
];
result = arrayList2.reduce(function (arr1, arr2) {
let isMatchFound = false;
arr1.forEach(function (list) {
if (arr2.type == list.type) {
list = Object.assign(list, arr2);
isMatchFound = true;
}
});
if (!isMatchFound) {
arr1.push(arr2);
}
return arr1;
}, arrayList1);
console.log('result', JSON.stringify(result));
result
应该是什么? - Jack Bashford列表1
和列表2
的典型大小是多少?它们总是相等的吗?在性能成为问题之前,我不会太担心它。当代码库非常庞大时,瓶颈通常出现在其他地方。如今,机器可以相当有效地处理循环等操作。 - Samuel Toh