javascript fill array with range

How to Fill an Array with a Range of Values using JavaScript

As a web developer, I often come across situations where I need to fill an array with a range of values. It could be for populating a dropdown list, generating a sequence of numbers, or any other use case that requires a series of values. In this article, I will share with you how to fill an array with a range of values using JavaScript.

Using a for loop

The simplest way to fill an array with a range of values is to use a for loop. Here's how:


let arr = [];
for (let i = 1; i <= 10; i++) {
  arr.push(i);
}
console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In this example, we declared an empty array arr and used a for loop to push values from 1 to 10 into the array. The loop starts from i = 1, increments i by 1 on each iteration, and stops when i <= 10 is no longer true.

Using the spread operator with Array.from()

An alternative way to fill an array with a range of values is to use the spread operator with the Array.from() method. Here's how:


let arr = [...Array(10).keys()].map(x => x + 1);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In this example, we used the Array() constructor to create an array of length 10 and then used the keys() method to generate an array of indices from 0 to 9. We then used the spread operator to spread the indices into a new array and applied the map() method to add 1 to each index and create an array of values from 1 to 10.

Using the Array.from() method with a map function

Another way to fill an array with a range of values is to use the Array.from() method with a map function. Here's how:


let arr = Array.from({length: 10}, (x, i) => i + 1);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In this example, we used the Array.from() method to create an array of length 10 and applied a map function to add 1 to each index and create an array of values from 1 to 10.

Conclusion

Filling an array with a range of values is a common task in JavaScript programming. Whether you prefer using a for loop or functional programming techniques like map(), you now have several options for accomplishing this task. I hope this article has been helpful in showing you how to fill an array with a range of values using JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe