Introduction
In this lab, we will explore how to initialize an array with reversed range using JavaScript. We will learn how to use the Array.from() and Array.prototype.map() methods to create an array that contains numbers in a specified range, but in reverse order. We will also see how to set default values for the start and step parameters and use them to generate the desired output.
How to Initialize an Array with a Reversed Range in JavaScript
To initialize an array with a reversed range in JavaScript, use the following function:
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
This function creates an array containing the numbers in the specified range in reverse order. The start and end parameters are inclusive, and the step parameter specifies the common difference between the numbers in the range.
To use the function, call it with the desired end, start, and step values as arguments, like this:
initializeArrayWithRangeRight(5); // [5, 4, 3, 2, 1, 0]
initializeArrayWithRangeRight(7, 3); // [7, 6, 5, 4, 3]
initializeArrayWithRangeRight(9, 0, 2); // [8, 6, 4, 2, 0]
If you omit the start argument, it defaults to 0. If you omit the step argument, it defaults to 1.
Summary
Congratulations! You have completed the Initialize Array With Reversed Range lab. You can practice more labs in LabEx to improve your skills.