I am trying to create 4 Arrays from 1 array, the condition is that the elements must be equally distributed.
const users = [1,2,3,4,5,6];
const userBatch = new Array(4).fill([]);
users.forEach((user, index) => {
userBatch[index % 4].push(user);
});
the expected out put is userBatch
[
[1, 5],
[2, 6],
[3],
[4]
]
but its not happening, the value of userBatch
is
[
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
]
What is the error in this code?
-Update It works in this way
const users = [1,2,3,4,5,6];
const userBatch = [[],[],[],[]];
users.forEach((user, index) => {
userBatch[index % 4].push(user);
});
Can anybody please explain why?