Initialize Array With Range

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the implementation of a function called initializeArrayWithRange in JavaScript. This function initializes an array containing the numbers in a specified range, with the option to include a step value. We will learn how to use Array.from(), the map() function, and default parameter values to create a flexible and reusable function for generating arrays with a range of values.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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`") subgraph Lab Skills javascript/variables -.-> lab-28393{{"`Initialize Array With Range`"}} javascript/data_types -.-> lab-28393{{"`Initialize Array With Range`"}} javascript/arith_ops -.-> lab-28393{{"`Initialize Array With Range`"}} javascript/comp_ops -.-> lab-28393{{"`Initialize Array With Range`"}} end

Function to Initialize Array with Range

To initialize an array with a range of numbers, use the following function:

const initializeArrayWithRange = (end, start = 0, step = 1) => {
  const length = Math.ceil((end - start + 1) / step);
  return Array.from({ length }, (_, i) => i * step + start);
};

This function takes three arguments: end (required), start (optional, default value is 0), and step (optional, default value is 1). It returns an array containing the numbers in the specified range, where start and end are inclusive with their common difference step.

To use this function, simply call it with the desired range parameters:

initializeArrayWithRange(5); // [0, 1, 2, 3, 4, 5]
initializeArrayWithRange(7, 3); // [3, 4, 5, 6, 7]
initializeArrayWithRange(9, 0, 2); // [0, 2, 4, 6, 8]

This function uses Array.from() to create an array of the desired length, and then a map function to fill the array with the desired values in the given range. If you omit the second argument, start, it will use a default value of 0. If you omit the last argument, step, it will use a default value of 1.

Summary

Congratulations! You have completed the Initialize Array With Range lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like