【发布时间】:2019-06-16 17:01:01
【问题描述】:
我有两个数组对象(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应该是什么? -
这里的
use case是什么。list 1和list 2的典型大小是多少?他们总是平等的吗?在出现问题之前,我不会太担心性能。当代码库很大时,瓶颈通常在其他地方。这些天机器可以非常有效地处理loops等。 -
@JackBashford - 我得到了预期的输出。只是想以高效和性能的方式减少代码。
-
@SamuelToh,'list-1' 和 'list-2' 的大小将会改变.. 大多数情况下,list1 和 list2 的格式会有所不同。只是我添加了 smaple json 以供理解...
-
@RSKMR 元素的顺序是否固定,即 arrayList1 的第一个元素,然后是 arrayList2?
标签: javascript arrays node.js object