1

Array.prototype.map() returns a new array. I want to reference this new array inside the callback function passed as the argument to Array.prototype.map(). Can I do that?

Example

someArray.map(function(item, idx, arr) {
    return { theCreatedArray: xyz };
});

What should xyz be?

EDIT [Context]

Why do I want this? The object I create in the callback is of a type that relies on having a reference to the array that is referencing the object. I can't refactor this requirement so easily. I would rather satisfy it.

3
  • 1
    Why? What exactly you are trying to do? Commented Jan 28, 2015 at 15:39
  • 1
    "Can I do that?" No. The new array is returned by map, there is no way to access it during the process. Commented Jan 28, 2015 at 15:40
  • 2
    It helps people to provide more useful answers and guidance if you explain a little bit about the context of your question. What is it that you're trying to do? Commented Jan 28, 2015 at 15:42

1 Answer 1

4

You can't do it with .map(), but you can do it with .reduce():

someArray.reduce(function(rv, item, idx) {
  // rv is the return value, in this case your array
  rv.push({whatever: rv});
  return rv;
}, []);
Sign up to request clarification or add additional context in comments.

3 Comments

Should rv.push use {whatever: item} rather than rv? This creates an infinitely-nested list (run from my chrome console).
@ssube well it's just an example; the point is that rv is a reference to the array. (It's not necessarily a bad thing to have a data structure with cycles anyway.)
Excellent. Array.prototype.reduce is more capable than map, but is a more conceptually difficult function. I'll use this.

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.