15

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

2
  • 4
    Just use the underscore-function until you are certain that it is a performance issue. It is very readable and clean, so unless it is actually an issue, your "feeling of inefficiency" shouldn't stop you from moving on to more pressing issues :) Commented Mar 15, 2012 at 23:24
  • Completely true! I'm just curious, nonetheless. Commented Mar 15, 2012 at 23:25

1 Answer 1

25

The Array#map() method.

var arr = arr.map(fn);

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

Sign up to request clarification or add additional context in comments.

1 Comment

If you're using Node.js you know what JS Interpreter you are using, thus you know that things from ECMAScript5 are implemented... which includes Array#map :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.