I like to combine numbers at every 4th index of an array. In the following oversimplified example, I did using "for" loop. Instead of that, I like to learn how to use "map" to achieve the same result. Thanks for any help!
function test() {
var array = [1, 2, 3, 4, 5, 6, 7, 8], arrayNew = [];
for (var n = 0; n < 4; ++n)
arrayNew[n] = array[n] + array[n + 4];
console.log(arrayNew)
}
To use
.map
, you could iterate the slice of the array that omits the first four elements. During that iteration, the loop index will be 4 units less, so you can grabarray[i]
and combine it with the currently iterated value from the slice:If you want to add more than just two values, but want to also add the value at 2n, 3n, ...etc, then you need a nested loop. Here
.map
is of less use. I would "map" with the use ofArray.from
, which has a callback function that performs a mapping. Secondly, the sum that has a dynamic number of terms can be performed withreduce
: