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?
.fillwith non-primitives; doing that creates a single of the passed object in memory. Then, when you iterate over the array, if you mutate the object at any index, it'll appear that every index object gets mutated, because all indicies point to the same object. UseArray.frominstead.filltoArray.frominstead. Can't use.fillwith non-primitives (in most cases).