map() is not saving the new elements

Viewed 477

Write a function incrementByIndex that accepts and array of nested arrays that hold numbers as values and returns an array were each element of the nested arrays is incremented by the index of that nested array.

Make sure to use the correct higher order functions

the first nested array's values were incremented by 0 since it is the first index, second nested array was incremented by 1 and last one by 2

incrementByIndex([
  [1, 2, 3],
  [2, 7, 9],
  [10, 3, 44],
]); // => [[1, 2, 3], [3, 8, 10], [12, 5, 46]]

my code :

const incrementByIndex = function (array) { 
  
 array.forEach(function(el){
      el.map(function(elm){
        elm +el.indexOf(elm)
      })
      
    })
  return array;
  
};

the output is the original array , why is that ?

2 Answers

Because map doesn't alter the original array, it outputs the contents to a new one. You must assign the result of el.map() some other variable. Also, note that you're missing a return statement in the function you pass to map.

const incrementByIndex = function(array) {
  const newArray = [];
  array.forEach(function(el) {
    const mapResult = el.map(function(elm) {
      return elm + array.indexOf(el)
    })
    newArray.push(mapResult)

  })

  return newArray;

};

const result = incrementByIndex([
  [1, 2, 3],
  [2, 7, 9],
  [10, 3, 44],
]);

console.log(result); // [[1, 2, 3], [3, 8, 10], [12, 5, 46]]

map doesn't actually alter the array it's acting on. It returns a new array transformed according to the function you give it. You weren't doing anything with that return value, so anything that the map does in your example is lost.

You can't actually use mutation here as the elements are numbers and these are immutable. One simple solution is below, which does use map, on both the outer and inner arrays, to return the overall array transformed in the way you want. Note that rather than using indexOf I am exploiting the fact that the index is available as the second argument of the callback passed to map.

const incrementByIndex = function (array) { 
  return array.map((subarray, index) => {
    return subarray.map(el => el + index);
  });   
};

console.log(incrementByIndex([
  [1, 2, 3],
  [2, 7, 9],
  [10, 3, 44],
]));

Related