Create Array of Integers Between Two Numbers Inclusive in JavaScript/jQuery
Last Updated :
26 Jun, 2023
Improve
There are multiple approaches for creating an array of all integers between two numbers, inclusive, in JavaScript/jQuery. Here are some of the common methods:
- Using loop
- Using Array.from() method
- Using jQuery
Method 1: Using Loops
The for loop or while loop iterates through all the integers between the two given numbers and pushes them into an array.
Syntax:
for (statement 1 ; statement 2 ; statement 3){ code here... }
Example: In this example, we will see the use of for loop and push().
function createArray(start, end) {
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
let result = createArray(1, 5);
// Output: [1, 2, 3, 4, 5]
console.log(result);
Output
[ 1, 2, 3, 4, 5 ]
Method 2: Using Array.from() method
Use Array.from() method to create an array of all integers between two numbers, inclusive.
Syntax:
function createArray(start, end) { return Array.from({length: end - start + 1}, (_, index) => start + index); }
Example: In this example, we will see the use of Array.from() method.
function createArray(start, end) {
return Array.from({ length: end - start + 1 },
(_, index) => start + index);
}
let result = createArray(1, 5);
// Output: [1, 2, 3, 4, 5]
console.log(result);
Output
[ 1, 2, 3, 4, 5 ]
Method 3: jQuery approach using for loop
The program starts by defining the start and end of the numeric range as start and end respectively, which in this case are set to 3 and 9. By using a map we iterate between the number and get the value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<script src=
"http://code.jquery.com/jquery-3.1.0.min.js"
integrity=
"sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
// Start and end
let start = 3;
let end = 9;
// Create an array of all integers
// between start and end using jQuery
let range =
$.map(new Array(end - start + 1),
function (val, index) {
return index + start;
});
document.write("[" + range.join(", ") + "]");
</script>
</body>
</html>
Output:
.png)