Philipp
Philipp

Reputation: 11341

Change array index with array.map()

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"},
];
*/

Upvotes: 2

Views: 11916

Answers (2)

Redu
Redu

Reputation: 26161

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.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816272

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.

Upvotes: 3

Related Questions