Skip to main content

fill

Fills an array with the specified value.

If start and end arguments are provided, only the elements within that index range are replaced with the specified value.

Unlike the native fill function, it does not modify the original array but returns a new array.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/fill7,944,868.540.0001fastest
js built-in/fill7,067,972.900.0001-
lodash/fill2,568,241.580.0004slowest
  • modern-kit/fill
    • 1.12x faster than js built-in/fill
    • 3.09x faster than lodash/fill

Interface

typescript
function fill<T, U>(arr: T[] | readonly T[], target: U): U[];
function fill<T, U>(
arr: T[] | readonly T[],
target: U,
start: number,
): (T | U)[];
function fill<T, U>(
arr: T[] | readonly T[],
target: U,
start: number,
end: number,
): (T | U)[]

Usage

typescript
import { fill } from '@modern-kit/utils';

const arr = [1, 2, 3, 4, 5];
console.log(fill(arr, 'a')); // ['a', 'a', 'a', 'a', 'a']
console.log(fill(arr, 'a', 2)); // [1, 2, 'a', 'a', 'a']
console.log(fill(arr, 'a', 2, 3)); // [1, 2, 'a', 'a', 5]