Initialize Array While

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of initializing and filling an array with values generated by a function, while a specified condition is met. We will use the initializeArrayWhile function which takes two functions as arguments, a condition function and a mapping function. This lab will help you understand how to create a customized array based on a specific condition and mapping function.


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`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") subgraph Lab Skills javascript/variables -.-> lab-28392{{"`Initialize Array While`"}} javascript/data_types -.-> lab-28392{{"`Initialize Array While`"}} javascript/arith_ops -.-> lab-28392{{"`Initialize Array While`"}} javascript/comp_ops -.-> lab-28392{{"`Initialize Array While`"}} javascript/loops -.-> lab-28392{{"`Initialize Array While`"}} end

How to Initialize and Fill an Array with a While Loop in JavaScript

To start practicing coding in JavaScript, open the Terminal/SSH and type node.

The initializeArrayWhile function initializes and fills an array with values generated by a function while a condition is met. Here's how it works:

  1. Create an empty array called arr, an index variable called i, and an element called el.
  2. Use a while loop to add elements to the array using the mapFn function, as long as the conditionFn function returns true for the given index i and element el.
  3. The conditionFn function takes three arguments: the current index, the previous element, and the array itself.
  4. The mapFn function takes three arguments: the current index, the current element, and the array itself.
  5. The initializeArrayWhile function returns the array.

Here's the code:

const initializeArrayWhile = (conditionFn, mapFn) => {
  const arr = [];
  let i = 0;
  let el = mapFn(i, undefined, arr);
  while (conditionFn(i, el, arr)) {
    arr.push(el);
    i++;
    el = mapFn(i, el, arr);
  }
  return arr;
};

You can use the initializeArrayWhile function to initialize and fill an array with values. For example:

initializeArrayWhile(
  (i, val) => val < 10,
  (i, val, arr) => (i <= 1 ? 1 : val + arr[i - 2])
); // [1, 1, 2, 3, 5, 8]

Summary

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

Other JavaScript Tutorials you may like