Search code examples
javascriptarray-mapnth-element

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


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

    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 of Array.from, which has a callback function that performs a mapping. Secondly, the sum that has a dynamic number of terms can be performed with reduce:

    function accumulate(array, n) {
        const groups = Array.from({length: array.length / n});
        return Array.from({length: n}, (val, i) => 
            groups.reduce((sum, _, j) => sum + array[i + j*n], 0)
        );
    }
    
    const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
    console.log(accumulate(array, 4));