react js how to do array range

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


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


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


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.

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