Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through array of arrays and increment values into a new array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading