Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to map an array in node.js or JavaScript

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 :)

like image 856
Eric Avatar asked Mar 15 '12 23:03

Eric


People also ask

Can we use map on array in JavaScript?

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.

How do you clear a map in JavaScript?

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.

How do you map an array of objects in Node JS?

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.


1 Answers

The Array#map() method.

var arr = arr.map(fn);

_.map() is probably implemented in the same way.

like image 88
fent Avatar answered Oct 11 '22 15:10

fent