HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Initialize a JavaScript array with a sequence of generated values

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptwithgeneratedsequenceinitializearrayvalues

Problem

Have you ever needed to initialize an array with a sequence of generated values? Or perhaps you wanted to generate an array of values until a condition is met? While JavaScript's Array.prototype.map() may be your go-to solution, you might need to reach for some other tools to get the job done in some cases.
At the most basic level, you can use the Array() constructor and Array.prototype.map() to initialize an array with a sequence of values. As the Array() constructor results in an array of empty slots, you may need to use Array.prototype.fill() to fill it with null values first to avoid any weird behavior.
The previous code snippet assumed that the length of the array to be created is known in advance. But what if you want to initialize an array while a condition is met? For example, you might want to generate the Fibonacci sequence until you reach a certain number. In this case, you can use a while loop to initialize the array.
In this code snippet, we create an empty array, arr, an index variable i and an element el. We then use a loop to add elements to the array, using the mapFn function, as long as the conditionFn function returns true.
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.

Solution

const initializeMappedArray = (n, mapFn = (_, i) => i) =>
  Array(n).fill(null).map(mapFn);

initializeMappedArray(5); // [0, 1, 2, 3, 4]
initializeMappedArray(5, i => `item ${i + 1}`);
// ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']


The previous code snippet assumed that the length of the array to be created is known in advance. But what if you want to initialize an array while a condition is met? For example, you might want to generate the Fibonacci sequence until you reach a certain number. In this case, you can use a while loop to initialize the array.
In this code snippet, we create an empty array, arr, an index variable i and an element el. We then use a loop to add elements to the array, using the mapFn function, as long as the conditionFn function returns true.
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.
> [!TIP]
>
> You can easily alter the behavior of this function to add elements until the condition is met, using a do..while loop, instead.

Code Snippets

const initializeMappedArray = (n, mapFn = (_, i) => i) =>
  Array(n).fill(null).map(mapFn);

initializeMappedArray(5); // [0, 1, 2, 3, 4]
initializeMappedArray(5, i => `item ${i + 1}`);
// ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']
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]
const unfold = (fn, seed) => {
  let result = [],
    val = [null, seed];
  while ((val = fn(val[1]))) result.push(val[0]);
  return result;
};

const f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); // [-10, -20, -30, -40, -50]

Context

From 30-seconds-of-code: initialize-array-with-generated-sequence

Revisions (0)

No revisions yet.