Initialize an array with a single value in JavaScript
This post will discuss how to initialize an array with a single value in JavaScript.
There are several ways to create an array in JavaScript with all its elements initialized with a specific value:
1. Using Array Constructor
The idea is to use Array Constructor to create an array of specific length and then use the fill() method to assign each element in an array to a specific value.
|
1 2 3 4 5 6 7 8 9 |
var n = 5; var val = 0; var arr = Array(n).fill(val); console.log(arr); /* Output: [ 0, 0, 0, 0, 0 ] */ |
2. Using Array.prototype.map() function
Alternatively, you can initialize the array by calling the map() method on the array literal. The following code example shows how to implement this:
|
1 2 3 4 5 6 7 8 9 |
var n = 5; var val = 0; var arr = [...Array(n)].map(x => val); // Array(N).fill().map(x => val); console.log(arr); /* Output: [ 0, 0, 0, 0, 0 ] */ |
3. Using Array.from() function
The Array.from() method creates a new array instance from the specified array and optionally map each array element to a new value.
To create an array, the idea is to pass an empty object to the Array.from() method with length property defined. To initialize it with the specified value, map each element to a new value.
|
1 2 3 4 5 6 7 8 9 |
var n = 5; var val = 0; var arr = Array.from({length: n}, x => val); console.log(arr); /* Output: [ 0, 0, 0, 0, 0 ] */ |
4. Using Underscore Library
The Underscore library _.range method can generate a sequence of values in JavaScript. You can call the fill() method to fill the generated values with the given value.
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('underscore'); var n = 5; var val = 0; var arr = _.range(n).fill(val); console.log(arr); /* Output: [ 0, 0, 0, 0, 0 ] */ |
That’s all about initializing an array with a single value in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)