0

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?

Midhun G S
  • 906
  • 9
  • 22
  • Don't use `.fill` with 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. Use `Array.from` instead – CertainPerformance Sep 14 '20 at 14:11
  • because your fill give four times the same array reference – Mister Jojo Sep 14 '20 at 14:18
  • @CertainPerformance: Although that duplicate helps explain why the original approach doesn't work, I think this question is equally about how to write code that does work. I'd suggest reopening. – Scott Sauyet Sep 14 '20 at 14:32
  • @ScottSauyet That question *does* show how to write code that does work - just change the `.fill` to `Array.from` instead. Can't use `.fill` with non-primitives (in most cases). – CertainPerformance Sep 14 '20 at 14:33
  • @CertainPerformance: I find that questionable. But as my notions on closing [don't seem](https://meta.stackoverflow.com/questions/400841) to be [the norm here](https://meta.stackoverflow.com/questions/398720), I'll just leave it there. – Scott Sauyet Sep 14 '20 at 14:56

1 Answers1

1

Use array.from and define the number to create the number of nested array

const users = [1, 2, 3, 4, 5, 6];
const userBatch = Array.from({
  length: 4
}, (v, i) => []);
users.forEach((user, index) => {
  userBatch[index % 4].push(user);
});
console.log(userBatch)
brk
  • 48,835
  • 10
  • 56
  • 78