Search code examples
javascriptarraysfunctionmethodsmap-function

JavaScript Destructive Map Function


I'm trying to make this map function a more destructive version of itself. Meaning the map function modifies the original array instead of a new one.

function map (array, callback) {
  var result = []
  for (var i = 0; i < array.length; i++) {
    result.push(callback(array[i]))
  }
  console.log("Array",array, "Result",result)
  return result
}

The console.log returns:

   Array [ 5, 2, 1 ] Result [ 6, 3, 2 ]

The array should be [5,2,1] and it's currently [6,3,2]


Solution

  • Your var result = [] creates a new array. If you want to modify the old array, you should assign to it (assign to properties of the array parameter):

    function map (array, callback) {
      array.forEach((item, i) => {
        array[i] = callback(item);
      });
      return array;
    }
    
    const arr = [1, 2];
    map(arr, e => e + 1);
    console.log(arr);

    Note that calling this function map might be a bit misleading, because Array.prototype.map does something similar, but creates an entirely separate array, like your original code is doing. You might want to call this function something other than map, perhaps changeEvery or something like that.