Skip to content

JavaScript array fill range | Example code

  • by

Use the fill() method with the map() function to fill JavaScript array in range. Or you can do a declarative approach while using Array.from like this:

arr = Array.from({length: 20}, (e, i)=> i)
console.log(arr)

Array.from() and Array.keys() require an ES6 polyfill in order to work in all browsers.

JavaScript array fill range

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    function range(start, end) {
      return Array(end - start + 1).fill().map((_, idx) => start + idx)
    }
    var result = range(0, 5);
    console.log(result);

  </script>

</body>
</html> 

Output:

JavaScript array fill range

Or you can use a combination of the Array.from() method and the fill() method to create an array filled with a range of values.

function fillRange(start, end) {
  return Array.from({ length: end - start + 1 }, (_, index) => start + index);
}

const range = fillRange(1, 10);
console.log(range); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ES6 creates an array with an increasing number

Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want an array of numbers 1..n that you can later loop through.

var foo = new Array(45); // create an empty array with length 45

then when you want to use it… (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
  document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
}

Spread

Making use of the spread operator (...) and keys method, enables you to create a temporary array of size N to produce the indexes, and then a new array that can be assigned to your variable:

var foo = [ ...Array(N).keys() ];

Fill/Map

You can first create the size of the array you need, fill it with undefined, and then create a new array using map, which sets each element to the index.

var foo = Array(N).fill().map((v,i)=>i);

Array.from

This should be initialized to a length of size N and populating the array in one pass.

Array.from({ length: N }, (v, i) => i)

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *