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.
4 Answers 4
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:
2 Comments
result = array1.map((arr) => arr.reduce((acc, value) => acc + value))In case number of elements is dynamic then,
let array1 = [[4000, 5000, 3000, 6000], [3000, 15000, 9000, 1000, 2000, 3000], [1000], [3000, 15000, 9000, 1000, 2000, 3000, 1000, 10000]];
let index = 0;
let newArray = [];
let maxElements = Math.max(...array1.map(arr => arr.length));
let arrayLength = array1.length;
while (index < maxElements) {
let total = 0;
for (let arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
let element = array1[arrayIndex][index]
if (element) total += element;
}
newArray.push(total);
index++;
}
console.log(newArray)
Comments
You may need a nested loop. So basically you will iterate array1 which holds both array2 and array3 and then in newArray you will see if specific index has a value. If so then you will add value with previous one
let array2 = [4000, 5000, 3000, 6000];
let array3 = [3000, 15000, 9000, 1000];
let array1 = [array2, array3];
let i = 0;
let newArray = []
while (i < array1.length) {
for (let j = 0; j < array1[i].length; j++) {
// if index of new array is unoccupied then set a value there
if (!newArray[j]) {
newArray[j] = array1[i][j]
} else {
// if index is occupied then add with previous value
newArray[j] = newArray[j] + array1[i][j]
}
}
i++;
}
console.log(newArray)
Comments
we used .map() to reference all of the element in an array, since our elements are also array but array of numbers and we want to add them all.. we use .reduce() method to add all of the array inside of our mapped array. result will be will still be an array, but the array inside it that consists of numbers are all added using reduce method. If you want to add everything.. just reduce it again. It will give a single value
a bit late but I hope this helps other peeps too
function addAll(array) {
return array.map((el) => {
return el.reduce((acc, curr) => {
return acc + curr;
});
});
}