Arrays can be initialised with data in a variety of ways in JavaScript. Let’s examine which methods are the easiest and most popular in this post.

 

Read this blog post or watch the video below to learn more about different ways to fill an array with initial values in JavaScript.

Down Arrow

#1 Fill an array with primitives

Let’s say, you want to initialize an array of elements 5 with the number 1. You can use the array.fill(initialValue) method to initialize an array. This method will return the modified array.

The thing that you need to keep in mind is the usage of array.fill(initialValue) in combination with Array(n) constructor.

const length = 5;
const newArray = Array(length).fill(1);
console.log(newArray); // Outputs [1,1,1,1,1]

Array(length) creates the sparse array. If you are not aware of sparse array, please read my previous blog: Sparse vs Dense Arrays in JavaScript. So Array(length).fill(1) basically modifies the array by putting 1 in every index of the array and finally returning the array like [1, 1, 1, 1, 1].

Array(length).fill(initialValue) is a convenient way to create arrays with the desired length and initialized them with a primitive value (number, string, boolean).

#2 Fill an array with objects

What if you need to add objects to an array? Whether you want the array filled with the initial object instances or with other instances, this need is significantly complicated.

#2.1 array.fill(initialValue)

If you want to initialize the array with the same object instance, then you can use array.fill() method.

const length = 4;
const myArray = Array(length).fill({ stage: 1 });
console.log(myArray); //[{stage : 1},{stage : 1},{stage : 1},{stage : 1}]

Array(length).fill({stage:1}) creates an array with length 4 and at the same time put the same object i.e. {stage : 1} on each index of the array.

The important thing that you need to remember is that each of the index is filled with same object instance. So if you want to change one index of the array, it will not only change that index, rather it will change every index of the array. Refer to the program below 

const length = 4;
const myArray = Array(length).fill({ stage: 1 });
console.log(myArray); //[{stage : 1},{stage : 1},{stage : 1},{stage : 1}]
myArray[2].stage = 3;
console.log(myArray); // [{stage : 3},{stage : 3},{stage : 3},{stage : 3}]

#2.2 array.from()

If you want to fill the array by creating copies from another array, then you can use array.from() method.

Array.from(array, mapperFunctionaccepts two arguments: an array (from which elements will be copied) and a mapperFunction (a function which will be called for each element of the original array).

Array.from() will invoke the mapperFunction on each item of the array and then pushes the result to a new array, and finally the newly mapped array.

const length = 4;
const oldArray = Array(length).fill({ stage: 1 });
console.log(oldArray); //[{stage : 1},{stage : 1},{stage : 1},{stage : 1}]
const newArray = Array.from(oldArray,()=>{return {stage : 4}});
console.log(newArray); //[{stage : 4},{stage : 4},{stage : 4},{stage : 4}] 

With this approach, if you change some element of the array, only that element is changed, not the entire array. 

const length = 4;
const oldArray = Array(length).fill({ stage: 1 });
console.log(oldArray); //[{stage : 1},{stage : 1},{stage : 1},{stage : 1}]
const newArray = Array.from(oldArray,()=>{return {stage : 4}});
console.log(newArray); //[{stage : 4},{stage : 4},{stage : 4},{stage : 4}]
newArray[2].stage = 5;
console.log(newArray); //[{stage : 4},{stage : 4},{stage : 5},{stage : 4}]

#2.3 array.map() with spread operator

When you use Array.length() to create an array, it creates a sparse array and using map() function on the sparse array skips the empty indexes from the array.

But using the spread operator you can transform a sparse array into an array with items initialized with undefined. After that, you can apply array.map() method on that array.

const length = 4;
const myArray = [...Array(length)].map(() => {
 return { value: 10 };
});
console.log(myArray); // [{ value: 10 }, { value: 10 }, { value: 10 }, { value: 10 }]

The expression […Array(length)] creates the array where items are initialized with undefined. And then applying map() to create new instances.

Conclusion

There are several good approaches to fill an array with initial values in JavaScript.

If you want to create an array using primitive values, the best method is to use Array (length). fill(initialValue).

If you want to create an array with object instances but don’t care if each item has the same object instance, use Array (length). The method to use is fill(initialObject).

Otherwise, you might use Array.from(Array.length, mapper) or […Array(length)] to populate an array with distinct object instances. map(mapper), where mapper is a function that, on each invocation, returns a new object instance.

1 Comment

Submit a Comment

Your email address will not be published.