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.
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:
- Create an empty array called
arr, an index variable calledi, and an element calledel. - Use a
whileloop to add elements to the array using themapFnfunction, as long as theconditionFnfunction returnstruefor the given indexiand elementel. - The
conditionFnfunction takes three arguments: the current index, the previous element, and the array itself. - The
mapFnfunction takes three arguments: the current index, the current element, and the array itself. - The
initializeArrayWhilefunction 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.