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?

5
  • 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 Commented Sep 14, 2020 at 14:11
  • because your fill give four times the same array reference Commented Sep 14, 2020 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. Commented Sep 14, 2020 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). Commented Sep 14, 2020 at 14:33
  • @CertainPerformance: I find that questionable. But as my notions on closing don't seem to be the norm here, I'll just leave it there. Commented Sep 14, 2020 at 14:56

1 Answer 1

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)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.