Home > database >  chunk array into multiple arrays
chunk array into multiple arrays

Time:04-03

I'm trying to chunk my array into 3 using this code

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

while (a.length > 0) {
  chunk = a.splice(0, 3);
  console.log(chunk);
}

but how can I get a result something like these

var array1 = ["a", "d", "g"];
var array2 = ["b", "e"];
var array3 = ["c", "f"];

CodePudding user response:

const a = ["a", "b", "c", "d", "e", "f", "g"];
const numberOfArrays = 3;
let arrays = Array.apply(null, Array(numberOfArrays)).map(it=>[])
a.forEach((value,i)=>{
  arrays[(i%numberOfArrays)].push(value);
})
console.log(arrays)

CodePudding user response:

Iterate over a and put the first element into array1, the second element into array2, the third element into array3, ...

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

const [array1, array2, array3] = a.reduce((acc, el, idx) => {
  acc[idx % 3].push(el);
  return acc;
}, [[], [], []]);

console.log(array1);
console.log(array2);
console.log(array3);

  • Related