"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Generate Number Ranges in JavaScript

Generate Number Ranges in JavaScript

Published on 2024-11-08
Browse:669

Generate Number Ranges in JavaScript

Generate an array of integers and fill it with consecutive values that begin with the start number and end with the end number inclusive.

Solution

function range(start, end) {
  const rangeArray = Array.from(
    {length: Math.ceil(end - start   1)}, (_, i) => start   i);

  return rangeArray;
}

console.log(range(10, 23));
console.log(range(5, 12));
console.log(range(89, 93));
console.log(range(42, 51));
console.log(range(73, 80));
> [10, 11, 12, 13, 14, 15,16, 17, 18, 19, 20, 21,22, 23]
> [5,  6,  7,  8, 9, 10, 11, 12]
> [89, 90, 91, 92, 93]
> [42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
> [73, 74, 75, 76, 77, 78, 79, 80]
Release Statement This article is reproduced at: https://dev.to/dindustack/generate-number-ranges-in-javascript-jbe?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3