2

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"];

4
  • the first chunk must always have three items? I doesnt matter if the array have 10 , 20 or more items? Commented Apr 2, 2022 at 18:48
  • @jabaa sorry for the confusion. Yes, I want to split it into 3 arrays, but the result must not be something like this one array1 = ["a", "b", "c", ...], please see above for the sample result. thank you Commented Apr 2, 2022 at 19:04
  • 1
    @MaikLowrey yes, it doesn't matter if the array has more than 3 or more elements, but the pattern or result must be something in the sample above. thank you Commented Apr 2, 2022 at 19:06
  • Iterate over a and put the first element into array1, the second element into array2, the third element into array3, ... The remainder operator could be helpful. Commented Apr 2, 2022 at 19:09

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

10 Comments

Can you explain what .map(it=>[]) do, please?
Array(numberOfArrays) create array with 3 values map(it=>[]) replace every element with empty array there is a great explanation i recommend you the read here stackoverflow.com/a/28599347/4267015
Thank you for answering. I tried with Array(3).fill([]); and got same [[],[],[]]. Afterwards i run your foreach: a.forEach((value,i)=>{ arrays[(i%3)].push(value); }) But i got completly wrong result. I dont understand it.
from msdnValue to fill the array with. (Note all elements in the array will be this exact value.) arrays and object are copied by ref in js all the elements in chunks as same ref to the array you pass to fill function, with map each cluser create new array
|
0

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);

1 Comment

@jabba this is also a good solution. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.