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 called i, and an element called el.
- 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.
- The
conditionFn function takes three arguments: the current index, the previous element, and the array itself.
- The
mapFn function takes three arguments: the current index, the current element, and the array itself.
- 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]