Reputation: 492
Is there anyway to merge two High Order Functions (HOFs) in Javascript? Basically I have two arrays using map function to get the item, then sum up with another item from another map function.
e.g.
const myArr1 = [
{ attr1: 5, attr2: 9, attr3: 3 },
{ attr1: 4, attr2: 1, attr3: 8 },
{ attr1: 1, attr2: 3, attr3: 1 },
]
const myArr2 = [
{ attr1: 7, attr2: 8, attr3: 5 },
{ attr1: 8, attr2: 2, attr3: 1 },
{ attr1: 3, attr2: 9, attr3: 7 },
]
const map1 = myArr1.map((item) => item);
const map2 = myArr2.map((item) => item);
I need to get something like this (expected):
const total = [{
attr1: map1.item.attr1 + map2.item.attr1;
attr2: map1.item.attr2 + map2.item.attr2;
attr3: map1.item.attr3 + map2.item.attr3;
}, {...}, {...}]
I tried this but did not work as expected:
const total = myArr1.map((item1) => {
myArr2.map((item2) => {
return [{
attr1: item1 + item2,
attr2: item1 + item2,
attr3: item1 + item2,
}, {...}, {...}]
})
});
Upvotes: 0
Views: 68
Reputation: 19564
You can use a zip
function to map over two arrays simultaneously:
import { zip } from "lodash";
const total = zip(myArr1, myArr2).map(([item1, item2]) => ({
attr1: item1.attr1 + item2.attr1,
attr2: item1.attr2 + item2.attr2,
attr3: item1.attr3 + item2.attr3,
}));
Alternatively, you can simplify further with mergeWith
:
import { add, mergeWith } from "lodash";
const total = mergeWith([], myArr1, myArr2, (item1, item2) =>
mergeWith({}, item1, item2, add)
);
Upvotes: 1
Reputation: 815
Here it is a simple solution to this
const myArr1 = [
{ attr1: 5, attr2: 9, attr3: 3 },
{ attr1: 4, attr2: 1, attr3: 8 },
{ attr1: 1, attr2: 3, attr3: 1 },
];
const myArr2 = [
{ attr1: 7, attr2: 8, attr3: 5 },
{ attr1: 8, attr2: 2, attr3: 1 },
{ attr1: 3, attr2: 9, attr3: 7 },
];
const myArr3 = myArr1.map((fi, i) => ({
attr1: fi.attr1 + myArr2[i].attr1,
attr2: fi.attr2 + myArr2[i].attr2,
attr3: fi.attr3 + myArr2[i].attr3,
}));
console.log(myArr3);
/** OUTPUT
[
{ attr1: 12, attr2: 17, attr3: 8 },
{ attr1: 12, attr2: 3, attr3: 9 },
{ attr1: 4, attr2: 12, attr3: 8 }
]
*/
Upvotes: 2