1

I have this array arr = [{id:1},{id:2},{id:3},{id:5},{id:5}] I want to modify array like index 0 - 1 is first, 2 -3 is second, 4 - 5 is third and so on

Result array: [first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]

How can I modify array in such type?

2 Answers2

1

The result you are expecting is not a valid array.

[first: [{},{}]]

It should be either an array like this

[[{},{}],[{},{}]]

or an object

{"first":[{},{}],"second":[{},{}]}

The code below converts your input to an array, it can be easily modified to an object if that's what you are looking for with some small modifications.

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
  if (index % 2 == 0) {
    acc.push([current]);
  } else {
    acc[Math.floor(index / 2)].push(current);
  }
  return acc;
}, []);

lastr2d2
  • 3,604
  • 2
  • 22
  • 37
0

You can use array.prototype.map. This example returns the id value of each multiplied by the number it exists in the array.

let arr = [{id:1},{id:2},{id:3},{id:5},{id:5}];
arr.map(function(item,index) {
    return item.id * index;
})

Try it out!

myjobistobehappy
  • 736
  • 5
  • 16