Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  179] [ 5]  / answers: 1 / hits: 28956  / 8 Years ago, tue, february 23, 2016, 12:00:00

I was toying a bit and was trying to instantiate a new array of length x, where all elements of that array were initialized to a value y:


var arr = new Array(x).fill(y);

This works well if the value of y is anything other than an object.
Meaning that if y is an object, the following is true:


var arr = new Array(2).fill({});
arr[0] === arr[1]; //is true;
arr[0].test = 'string';
arr[1].test === 'string'; //is also true;

Is there any way to state that a new object should be created for each element while using the fill-function? Or should I just convert it to a loop?


More From » arrays

 Answers
10

You can first fill the array with any value (e.g. undefined), and then you will be able to use map:



var arr = new Array(2).fill().map(u => ({}));


var arr = new Array(2).fill().map(Object);

[#63201] Sunday, February 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorw

Total Points: 484
Total Questions: 120
Total Answers: 107

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;