2

Is it somehow possible to iterate an array in JS using Array.map() and modify the index values of the resulting array?

// I start with this values:
var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

var arrResult = arrSource.map(function(obj, index) {
    // What to do here?
    return ???; 
});

/*
This is what I want to get as result of the .map() call:

arrResult == [
  7: {id:7, name:"item 1"}, 
  10: {id:10, name:"item 2"},
  19: {id:19, name:"item 3"},
];
*/
0

2 Answers 2

3

No. Array#map performs a 1:1 mapping (so to speak).

You'd have to create a new array and explicitly assign the elements to the specific indexes:

var arrResult = [];
arrSource.forEach(function(value) {
   arrResult[value.id] = value;
});

Of course you can use .reduce for that too.

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

3 Comments

Yes, alternatively map then sort.
@Vld: Not sure how either of these would help here.
Actually, you're right. I misread the question thinking OP wants to map then re-order.
0

Of course you can do it as follows;

var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

newArr = arrSource.map((e,i,a) => a[a.length-1-i]);
console.log(newArr)

Yes... always the source array gets mutated if you need some irregularities with Array.prototype.map() such as

var arrSource = [
  {id:7, name:"item 1"}, 
  {id:10, name:"item 2"},
  {id:19, name:"item 3"},
];

newArr = arrSource.map((e,i,a) => a[a.length] = e);
console.log(JSON.stringify(arrSource,null,4));

which is not surprising.

8 Comments

That just seems to reverse the order of elements.
@Felix Kling Yes.. or whatever order you like depending on your logic.
But that's not what the OP wants to do. The OP wants to assign arr[0] to arr[7], arr[1] to arr[10], etc.
@Felix Kling and in this particular snippet we are assigning arr[2] to arr[0]
Sure. The point is that you cannot assign to arbitrary indexes via .map. You can only assign to indexes that already have a value (i.e. exist). But even then, you cannot really control to which index something is assigned to. You have to think the other way round: What do I want to assign to index i? And since in your example index 7 will never be processed it's not possible to achieve what the OP wants with .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.