Divide an array into exact divisions

2

I have an arrangement of 10 elements and I want to divide them from 2 into 2 elements.

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let res = [];
let parcial = [];
for (let i = 0; i < array.length; i++) {
  parcial.push(array[i]);

  if (i % 2 === 0) {
    res.push(parcial);
    parcial = [];
  }
}
console.log(res);

The expected result is: [[1,2],[3,4],[5,6],[7,8],[9,0]] , but what I get is

[
  [1],
  [2, 3],
  [4, 5],
  [6, 7],
  [8, 9]
] 

How do I solve it?

    
asked by hubman 16.10.2018 в 18:04
source

1 answer

2

The problem is the use of the index: the first position is 0, the second is 1, so the condition to insert the pair should be i % 2 === 1 (odd):

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let res = [];
let parcial = [];
for (let i = 0; i < array.length; i++) {
  parcial.push(array[i]);

  if (i % 2 === 1) {
    res.push(parcial);
    parcial = [];
  }
}
console.log(res);

Another solution would be to use slice :

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

function trocear(array,tamTrozo) {
  let result=[];

  for (let i=0; i < array.length; i+=tamTrozo) {
    result.push(array.slice(i,i+tamTrozo));
  }
  return result;
}

console.log(trocear(array,2));
console.log(trocear(array,3));
console.log(trocear(array,5));
    
answered by 16.10.2018 / 18:09
source