Is there a function like map() in JS that stores the returns in the original array, instead of making a new array? If not, what would be the most efficient way to do this?
1 Answer
Just use .forEach() instead:
myArray.forEach(function(value, index, array) {
array[index] = ... // some mutation of value
});
The exact same code would still work with .map (which invokes the callback with the same three parameters and therefore allows in-place mutation) but .forEach avoids the overhead of creating a new array, only to have it thrown away again immediately.
Note also that whilst one could just refer to myArray inside the callback, it's much more efficient not to. Having the array parameter passed to the callback allows the callback to manipulate or access the original array without requiring it to be in the lexical scope (although using this to insert or delete elements would be ill advised)
forEach.