Initialize Array with Reversed Range

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28394{{"`Initialize Array with Reversed Range`"}} javascript/data_types -.-> lab-28394{{"`Initialize Array with Reversed Range`"}} javascript/arith_ops -.-> lab-28394{{"`Initialize Array with Reversed Range`"}} javascript/comp_ops -.-> lab-28394{{"`Initialize Array with Reversed Range`"}} javascript/higher_funcs -.-> lab-28394{{"`Initialize Array with Reversed Range`"}} end

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.

Other JavaScript Tutorials you may like