Skip to content
the poor coder

react js how to do array range

Poor Man
Published
Reading time
2 min read
On this page

How to Do Array Range in React JS#

Array range is a common feature used in programming to create an array of numbers with a certain range. In React JS, there are multiple ways to achieve array range. Here are some of the ways:

1. Using for loop and push function#

Text

const rangeArray = (start, end) => {
  let arr = [];
  for (let i = start; i <= end; i++) {
    arr.push(i);
  }
  return arr;
};

console.log(rangeArray(1,5)); //output: [1, 2, 3, 4, 5]

In the above code, we are using a for loop to iterate through the given range and push each number into the array.

2. Using Array.from method#

Text

const rangeArray = (start, end) => {
  return Array.from({length: end - start + 1}, (_, i) => start + i);
};

console.log(rangeArray(1,5)); //output: [1, 2, 3, 4, 5]

In the above code, we are using the Array.from method which creates a new array from an array-like or iterable object. We are passing an object with the length property as the first argument and a function as the second argument to map each value to its index.

3. Using spread operator and Array.keys method#

Text

const rangeArray = (start, end) => {
  return [...Array(end - start + 1).keys()].map(i => i + start);
};

console.log(rangeArray(1,5)); //output: [1, 2, 3, 4, 5]

In the above code, we are using the spread operator to spread an array created by the Array.keys method which creates an array of keys from 0 to the given length. We are then using map method to add the start value to each index.

These are some of the ways you can create an array range in React JS. Choose the method that suits your needs and coding style.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC