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?

4
  • Have a look at w3 schools forEach documentation Commented Dec 22, 2020 at 6:45
  • Could you please give more detail for the output generate rules? Commented Dec 22, 2020 at 6:51
  • You can use forEach, map, a while loop, or a for loop. Commented Dec 22, 2020 at 6:55
  • Does this answer your question? Convert Array to Object Commented Dec 22, 2020 at 7:23

2 Answers 2

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

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

Comments

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!

Comments

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.