Tormod Smith Tormod Smith - 5 months ago 7
Javascript Question

How do you split an array into array pairs in JavaScript?

I want to split an array into pairs of arrays

so var arr=[2,3,4,5,6,4,3,5,5]

would be newarr =[[2,3],[4,5],[6,4],[3,5],[5]]

Answer

A slightly different approach than using a for loop for comparison. To avoid modifying the original array slice makes a shallow copy since JS passes objects by reference.

function pairArray(a) {
  var temp = a.slice();
  var arr = [];

  while (temp.length) {
    arr.push(temp.splice(0,2));
  }

  return arr;
}

var array = [2,3,4,5,6,4,3,5,5];
var newArr = pairArray(array);

function pairArray(a) {
  var temp = a.slice();
  var arr = [];

  while (temp.length) {
    arr.push(temp.splice(0,2));
  }

  return arr;
}

document.write('<pre>' + JSON.stringify(newArr) + '</pre>');