-1

I have an array of objescts like this

  const arrayOne = [
  { id: 'call_1', callDuration: 3 },
  { id: 'call_2', callDuration: 5 },
  { id: 'call_3', callDuration: 4 },
  { id: 'call_4', callDuration: 8 },
  { id: 'call_5', callDuration: 3 },
  { id: 'call_6', callDuration: 4 },
  { id: 'call_7', callDuration: 6 },
  { id: 'call_8', callDuration: 7 },
  { id: 'call_9', callDuration: 25 },
  { id: 'call_10', callDuration: 25 },
];

out of arrayOne I need to create the following one:

    const arrayTwo = [
  [
    { id: 'call_1', callDuration: 3 },
    { id: 'call_2', callDuration: 5 },
  ],
  [
    { id: 'call_2', callDuration: 5 },
    { id: 'call_3', callDuration: 4 },
  ],
  [
    { id: 'call_3', callDuration: 4 },
    { id: 'call_4', callDuration: 8 },
  ],
  [
    { id: 'call_4', callDuration: 8 },
    { id: 'call_5', callDuration: 3 },
  ],
  [
    { id: 'call_5', callDuration: 3 },
    { id: 'call_6', callDuration: 4 },
  ],
  [
    { id: 'call_6', callDuration: 4 },
    { id: 'call_7', callDuration: 6 },
  ],
  [
    { id: 'call_7', callDuration: 6 },
    { id: 'call_8', callDuration: 7 },
  ],
  [
    { id: 'call_8', callDuration: 7 },
    { id: 'call_9', callDuration: 25 },
  ],
  [
    { id: 'call_9', callDuration: 25 },
    { id: 'call_10', callDuration: 25 },
  ],
];

What I want is basically to create a new array of arrays that contain the objects. I am not sure how to approach this one. Let me know if you have any ideas.

John John
  • 1,305
  • 2
  • 16
  • 37

1 Answers1

1

You can do it by this

const arrayTwo = [];
for(let i=0; (i+1) < arrayOne.length; i+=1) {
 const temp = [ arrayOne[i],  arrayOne[i+1] ];
 arrayTwo.push(temp);
}
Amaarockz
  • 4,348
  • 2
  • 9
  • 27
  • not sure why i am getting this error `VM415:2 Uncaught ReferenceError: call_1 is not defined` – John John Nov 17 '20 at 05:27
  • Try printing a console.log(arrayTwo) after the for loop ...if it's printing the array properly then problem is with the part after the for loop – Amaarockz Nov 17 '20 at 05:29
  • tried but it is not working. may be I am doing something wrong. It does looks correct but I am missing something – John John Nov 17 '20 at 05:34
  • 1
    it was my mistake. I had to fix the original array and put a string – John John Nov 17 '20 at 06:03