hans-t hans-t - 7 months ago 6
Javascript Question

What's the equivalent way in ES6 of making list of duplicated elements?

In Python, I can do:

l = [{'d': 3}] * 5
to get
[{'d': 3}, {'d': 3}, {'d': 3}, {'d': 3}, {'d': 3}]
.

What is the equivalent way of doing this in ES6, that actually clones the objects and not just copying the reference?

edit: Basically, is there a shortcut in ES6 to make the following array:

const arr = [
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
{"d": 3},
];


?

Oka Oka
Answer

The literal equivalent would be

const arr = Array(5).fill({d: 3}); 

this will fill the array with the same object reference, five times.

To get clones is slightly more involved. Consider:

Array.apply(null, Array(5)).map(_ => ({d: 3}));

or

Array(5).fill(0).map(_ => ({d: 3}));