1

For example i have following array:

var a = ["a", "b", "c", "d", "e", "f", "g", "h"];

and i have another empty array like following:

var b = [];

Here my question comes, I need to push variables from a to b but b must contain arrays in a such way:

b = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"]];

Thanks in advance.

Star
  • 3,222
  • 5
  • 32
  • 48
Yusufbek
  • 2,180
  • 1
  • 17
  • 23

1 Answers1

1

You should use slice method which returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

let a = ["a", "b", "c", "d", "e", "f", "g", "h"];
let b = [];
let chunk=2;
for (i=0,j=a.length; i<j; i+=chunk) {
    chunkArray = a.slice(i,i+chunk);
    b.push(chunkArray);
}
console.log(b);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128