Code Snippets
/

Generate Arrays from Args, Random, and Higher-Order Inputs

Generate Arrays from Args, Random, and Higher-Order Inputs

Three array-generation idioms that come up constantly: building a fixed-length array of computed values (random fillers, ranges, defaults), turning function arguments into an array, and writing higher-order functions that return array transformers parameterized by a constant. Each is one line of code, but the patterns generalize to test fixtures, configuration, and small DSLs.

JavaScript
Medium
3 snippets
arrays
higher-order-functions
functions

311 views

8

// 5 random floats in [0, 1).
const randoms5 = Array.from({ length: 5 }, () => Math.random());
console.log(randoms5);
// [0.x, 0.y, 0.z, 0.w, 0.v]   (5 unique floats)

// 5 random integers in [0, 99].
const randomInts = Array.from({ length: 5 }, () => Math.floor(Math.random() * 100));
console.log(randomInts);
// [42, 7, 88, 13, 55]   (example output)

// The mapping function receives (_, i), so you can build index-based values.
const squares = Array.from({ length: 5 }, (_, i) => i * i);
console.log(squares); // [0, 1, 4, 9, 16]

// Same idea with a fixed default value.
const zeros = new Array(5).fill(0);
console.log(zeros); // [0, 0, 0, 0, 0]

Array.from({ length: n }, fn) is the cleanest way to produce a fixed-length array. The first argument is an array-like with a length, the second is a mapping function called once per slot with (value, index). Use it for random fillers, index-based sequences (i => i * i), or any computed default. For a constant value, new Array(n).fill(value) is shorter, but be careful: passing an OBJECT to fill shares the same reference across every slot, so new Array(3).fill({})[0] === new Array(3).fill({})[1] is true for the same call. Use Array.from({ length: n }, () => ({})) to get fresh objects per slot.