David Groomes
David Groomes

Reputation: 2383

Inside the callback in Array.prototype.map, reference the new array

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.

Upvotes: 1

Views: 66

Answers (1)

Pointy
Pointy

Reputation: 413717

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;
}, []);

Upvotes: 4

Related Questions