How to get a range numbers from given numbers in javascript

How to Get a Range of Numbers from Given Numbers in JavaScript

If you're working with JavaScript and need to get a range of numbers from a given set of numbers, there are different approaches you can take. Here are a few ways:

Method 1: Using a for loop

One way to get a range of numbers is to use a for loop. Here's an example:

function getRange(start, end) {
  var range = [];
  
  for (var i = start; i <= end; i++) {
    range.push(i);
  }
  
  return range;
}

var myRange = getRange(1, 5);
console.log(myRange); // [1, 2, 3, 4, 5]

In this example, we define a function called getRange that takes two arguments: start and end. The function creates an empty array called range, and then uses a for loop to iterate over the range of numbers from start to end, pushing each number into the range array. Finally, the function returns the range array.

Method 2: Using the Array.from() method

Another way to get a range of numbers is to use the Array.from() method, which creates a new array from an iterable object. Here's an example:

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

var myRange = getRange(1, 5);
console.log(myRange); // [1, 2, 3, 4, 5]

In this example, we define a function called getRange that takes two arguments: start and end. The function creates a new array using Array.from(), passing in an object that has a length property equal to the difference between end and start, plus one. We also pass in a function that takes two arguments: the current element's value (which we don't use) and its index, which we add to the starting value to get the current number in the range.

Method 3: Using the spread operator

A third way to get a range of numbers is to use the spread operator, which allows you to expand an iterable object into a list of arguments. Here's an example:

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

var myRange = getRange(1, 5);
console.log(myRange); // [1, 2, 3, 4, 5]

In this example, we define a function called getRange that takes two arguments: start and end. We use the Array() constructor to create a new array with a length equal to the difference between end and start, plus one, and the keys() method to get an iterable object representing the indices of the array. We then use the spread operator to expand this iterable object into an array, and use the map() method to add the starting value to each index to get the current number in the range. Finally, we return the resulting array.

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