Let's say I have a function and an array. I want to modify the array by applying the function to each entry in the array. The function does NOT modify the value directly; it returns a new value.
In pseudo-code,
for (entry in array) {
entry = function(entry);
}
There are a couple ways to do this that occurred to me:
for (var i = 0; i < arr.length; i++) {
arr[i] = fn(i);
}
Or, since I am using node.js and have underscore built in:
arr = _.map(arr, fn);
But this both seem a little clunky. The standard "for" block feels overly verbose, and the _.map function re-assigns the entire array so feels inefficient.
How would you do this?
Yes, I am aware I'm overthinking this :)
JavaScript | Array map() MethodThe map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.
Map.clear() Method in JavaScript clear() method in JavaScript is used for the removal of all the elements from a map and make it empty. It removes all the [key, value] from the map. No arguments are required to be sent as parameters to the Map. clear() method and it returns an undefined return value.
The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.
The Array#map() method.
var arr = arr.map(fn);
_.map()
is probably implemented in the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With