sse sse - 21 days ago 10
Javascript Question

How to Splice array in Javascript without returning reversed data

I'm new to JavaScript. I have an array:

var test = [
{data1},
{data2},
{data3},
{data4},
{data5}
];


So what I did is

var test1 = [];
while(test.lenght){
test1.push(test.splice(0-2));
}


But the result is

test1[0] = [{data4},{data5}];
test1[1] = [{data2},{data3}];
test1[2] = [{data1}];


I want to splice it into like this

test1[0] = [{data1},{data2}];
test1[1] = [{data3},{data4}];
test1[2] = [{data5}];


How can I achieve this?

Answer

Update Array#splice method with arguments as 0 and 2 for removing first 2 elements.

var test = [
  'data1',
  'data2',
  'data3',
  'data4',
  'data5'
];

var test1 = [];
while (test.length) {
  test1.push(test.splice(0, 2));
}

console.log(test1)


UPDATE : If you don't want to update the original array then use Array#slice method.

var test = [
  'data1',
  'data2',
  'data3',
  'data4',
  'data5'
];

var test1 = [];
for (var i = 0, count = Math.ceil(test.length / 2); i < count; i++) {
  test1.push(test.slice(i * 2, i * 2 + 2));
}

console.log(test1)

// or alternate method with updated for loop conditions

var test2 = [];
for (var i = 0; i < test.length; i += 2) {
  test2.push(test.slice(i, i + 2));
}

console.log(test2)