What is filled-array?
The filled-array npm package is a utility that allows you to create an array filled with a specified value. It is useful for initializing arrays with default values or for creating arrays of a specific length with repeated elements.
What are filled-array's main functionalities?
Create an array filled with a specific value
This feature allows you to create an array of a specified length, filled with a given value. In the code sample, an array of length 5 is created, with each element being the string 'x'.
const filledArray = require('filled-array');
const result = filledArray('x', 5);
console.log(result); // ['x', 'x', 'x', 'x', 'x']
Create an array using a function to generate values
This feature allows you to create an array where each element is generated by a function. The function receives the index of the element as an argument. In the code sample, an array of length 4 is created, with each element being twice its index.
const filledArray = require('filled-array');
const result = filledArray((index) => index * 2, 4);
console.log(result); // [0, 2, 4, 6]
Other packages similar to filled-array
array-fill
The array-fill package provides similar functionality to filled-array, allowing you to fill an existing array with a specified value. Unlike filled-array, which creates a new array, array-fill modifies an existing one.
lodash
Lodash is a popular utility library that includes a method _.fill, which can fill elements of an array with a specified value. While lodash offers a broader range of utilities beyond array filling, its _.fill method is comparable to filled-array's functionality.
array.prototype.fill
This is a polyfill for the native Array.prototype.fill method, which is part of the ECMAScript 2015 (ES6) standard. It provides similar functionality to filled-array, allowing you to fill an array with a static value. Unlike filled-array, this method is built into modern JavaScript engines.
filled-array
Returns an array filled with the specified input
Install
npm install filled-array
Usage
import filledArray from 'filled-array';
filledArray('x', 3);
filledArray(0, 3);
filledArray(index => {
return (++index % 3 ? '' : 'Fizz') + (index % 5 ? '' : 'Buzz') || index;
}, 15);
API
filledArray(fillValue, count)
fillValue
Type: unknown
The value to fill the array with.
You can pass a function to generate the array items dynamically. The function is expected to return the value for each iteration and will be called with the following arguments: index, the count you passed in, and the filled array thus far.
count
Type: number
(non-negative integer)
The number of items to fill the array with.