I’m struggling with looping through an array of arrays and returning a new array with the incremented value of the result.
Here’s the concept:
let array1 = [array1, array2];
let array2 = [4000,5000,3000,6000];
let array3 = [3000, 15000, 9000, 1000];
let i = 0;
let newArray = []
while (i < array1.length) {
// how do I get the combined value in a new array so that newArray[0] = 7000, newArray[1] = 20000 etc.
}
Array1 comes from an API and is an unknown number of arrays.
>Solution :
This should work for any number of sub arrays. Here it is assumed that array1 contains 4 arrays.
let array2 = [4000, 5000, 3000, 6000]
let array3 = [3000, 15000, 9000, 500]
let array4 = [5000, 15000, 4000, 2000]
let array5 = [6000, 25000, 5000, 8000]
let array1 = [array2, array3, array4, array5]
const result = array1.reduce((acc, curr) => {
return acc.map((item, index) => item + curr[index])
})
console.log(result)
References: