Marc
Marc

Reputation: 297

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]

Upvotes: 1

Views: 1495

Answers (2)

Shuvro
Shuvro

Reputation: 242

You can follow this code...I hope your problem solved

function map(array, callback) {
    var result=[]
    for (var i = 0; i < array.length; i++) {
       result.push(callback(array[i]))
    }
    console.log(result)
}
map([5, 2, 1], (value) => {
   return value
})

Upvotes: 0

Snow
Snow

Reputation: 4097

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.

Upvotes: 5

Related Questions