What is lodash.castarray?
The lodash.castarray package is a utility function from the Lodash library that ensures a value is wrapped in an array. If the value is already an array, it returns the value unchanged. This is useful for normalizing inputs to functions that expect arrays.
What are lodash.castarray's main functionalities?
Cast a single value to an array
This feature takes a single value and returns it as an array. If the input is not an array, it wraps the value in an array.
const castArray = require('lodash.castarray');
const result = castArray(1);
console.log(result); // [1]
Return an array unchanged
This feature checks if the input is already an array and returns it unchanged.
const castArray = require('lodash.castarray');
const result = castArray([1, 2, 3]);
console.log(result); // [1, 2, 3]
Handle various data types
This feature demonstrates that lodash.castarray can handle various data types, including strings, objects, and null values, wrapping them in an array.
const castArray = require('lodash.castarray');
console.log(castArray('string')); // ['string']
console.log(castArray({ key: 'value' })); // [{ key: 'value' }]
console.log(castArray(null)); // [null]
Other packages similar to lodash.castarray
arrayify
The arrayify package provides similar functionality by converting a value to an array if it is not already one. It is a lightweight alternative to lodash.castarray and is useful for normalizing inputs.
ensure-array
The ensure-array package ensures that the input is an array. If the input is not an array, it wraps it in one. This package is similar to lodash.castarray but focuses solely on this functionality without the additional utilities provided by Lodash.
to-array
The to-array package converts an array-like object or a single value to an array. It is useful for normalizing inputs and is similar to lodash.castarray in its core functionality.
lodash.castarray v4.4.0
The lodash method _.castArray
exported as a Node.js module.
Installation
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save lodash.castarray
In Node.js:
var castArray = require('lodash.castarray');
See the documentation or package source for more details.