Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.fill() with object passes reference and not new instance

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?

like image 650
Koen Morren Avatar asked Feb 23 '16 13:02

Koen Morren


People also ask

How do you fill an array of objects?

In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.

Which array prototype function returns a reference to a new array every time?

Definition and Usage. The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.

What is fill in array?

The fill() method fills specified elements in an array with a value. The fill() method overwrites the original array. Start and end position can be specified. If not, all elements will be filled.

Which method is used to add new element to an array of objects?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed.


1 Answers

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); 
like image 78
Oriol Avatar answered Sep 24 '22 12:09

Oriol