JavaScript Snippet

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

Difficulty: Medium

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.

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

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.