Initialize array while
JavaScript, Array · Jun 20, 2023

Initializes and fills an array with values generated by a function, while a condition is met.
- Create an empty array,
arr
, an index variablei
and an elementel
. - Use a
while
loop to add elements to the array, using themapFn
function, as long as theconditionFn
function returnstrue
for the given indexi
and elementel
. - The condition function,
conditionFn
, takes three arguments: the current index, the previous element and the array itself. - The mapping function,
mapFn
, takes three arguments: the current index, the current element and the array itself.
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;
};
initializeArrayWhile(
(i, val) => val < 10,
(i, val, arr) => (i <= 1 ? 1 : val + arr[i - 2])
); // [1, 1, 2, 3, 5, 8]
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.