How to Splice array in Javascript without returning reversed data -
i'm new javascript. have array:
var test = [ {data1}, {data2}, {data3}, {data4}, {data5} ];
so did is
var test1 = []; while(test.lenght){ test1.push(test.splice(0-2)); }
but result is
test1[0] = [{data4},{data5}]; test1[1] = [{data2},{data3}]; test1[2] = [{data1}];
i want splice this
test1[0] = [{data1},{data2}]; test1[1] = [{data3},{data4}]; test1[2] = [{data5}];
how can achieve this?
update array#splice
method arguments 0
, 2
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 don't want update original array use array#slice
method.
var test = [ 'data1', 'data2', 'data3', 'data4', 'data5' ]; var test1 = []; (var = 0, count = math.ceil(test.length / 2); < count; i++) { test1.push(test.slice(i * 2, * 2 + 2)); } console.log(test1) // or alternate method updated loop conditions var test2 = []; (var = 0; < test.length; += 2) { test2.push(test.slice(i, + 2)); } console.log(test2)
Comments
Post a Comment