Aller au contenu principal

fill()

fill<T>(array, value, start?, end?): T[]

Fills elements of array with value from start up to, but not including, end.

WHY WRAPPING NATIVE?

Unlike the native Array.fill() which mutates the original array, this function returns a new array, preserving immutability. See Design Philosophy

remarque

For ES2023+, consider using Array.toFilled().


Type Parameters

T: T

The type of elements in the array.


Parameters

array: readonly T[]

The array to fill.

value: T

The value to fill array with.

start?: number

The start position.

end?: number

The end position.


Returns: T[]

A new array with the filled values.


Since

2.0.0


Performance

O(n) time & space — three-pass manual copy with fill range.


Also known as

fill (Lodash, es-toolkit) · replaceOption (Effect) · ❌ (Remeda, Radashi, Ramda, Modern Dash, Antfu)


Example

const numbers = [1, 2, 3, 4, 5];

const filled = fill(numbers, 0, 1, 3);
console.log(filled); // [1, 0, 0, 4, 5]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)

How it works?

Replaces elements in a range with a specified value. Unlike native Array.fill(), returns a new array (immutable).


Use Cases

Initialize game board or grid 📌

Create an array filled with a static initial value. Immutable alternative to new Array(n).fill(v).

// Create a row of empty slots
const emptyRow = fill(new Array(5), "empty");
// => ["empty", "empty", "empty", "empty", "empty"]

Reset status flags

Reset a specific range of values within an array without mutating the original. Useful for bulk updates or resetting state.

const steps = ["done", "done", "error", "pending"];

// Reset steps 1 and 2 (indices 1 to 3) to "retry"
const retrying = fill(steps, "retry", 1, 3);
// => ["done", "retry", "retry", "pending"]