Reputation: 641
I have two arrays
let arr1 = [{a: 1, b: 2}, {a: 3, b: 4}]
let arr2 = [{c: 5}, {c: 6}]
I am trying to create a new array such that each value in arr1 is mapped to each value in arr2. Something like this,
[1-2-5, 1-2-6, 3-4-5, 3-4,6]
I know that this can be done using two for loops. One to loop on arr1 and a nested for loop that loops over arr2. But I am looking for a cheap and efficient method to do it. Any help would be much appreciated! Thanks in advance. Cheers!
Upvotes: 0
Views: 175
Reputation: 367
You could use map()
to achieve this.
let arr1 = [{a: 1, b: 2}, {a: 3, b: 4}]
let arr2 = [{c: 5}, {c: 6}]
const result = arr1.flatMap((x) => {
return arr2.map((y) => `${x.a}-${x.b}-${y.c}`);
});
console.log(result);
Because you can't use -
in a number, storing the values in separate arrays would be an option.
let arr1 = [{a: 1, b: 2}, {a: 3, b: 4}]
let arr2 = [{c: 5}, {c: 6}]
const result = arr1.flatMap((x) => {
return arr2.map((y) => [x.a, x.b, y.c]);
});
console.log(result);
Upvotes: 2