How to use javascript map to combine numbers at every nth element?

Advertisements

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)
}

>Solution :

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 grab array[i] and combine it with the currently iterated value from the slice:

const array = [1, 2, 3, 4, 5, 6, 7, 8];
const result = array.slice(4).map((val, i) => array[i] + val);
console.log(result);

Leave a ReplyCancel reply