Casts value as an array if it's not one
npx @tessl/cli install tessl/npm-lodash--castarray@4.4.0Lodash CastArray provides a single utility function that converts any value to an array if it's not already one. It ensures consistent array-type outputs regardless of input type, making it ideal for normalizing function parameters that can accept either single values or arrays.
npm install lodash.castarrayvar castArray = require('lodash.castarray');For ES modules (if using a bundler):
import castArray from 'lodash.castarray';var castArray = require('lodash.castarray');
// Convert single values to arrays
castArray(1); // => [1]
castArray('hello'); // => ['hello']
castArray({ a: 1 }); // => [{ a: 1 }]
castArray(null); // => [null]
castArray(undefined); // => [undefined]
// Arrays are returned unchanged (reference preserved)
var arr = [1, 2, 3];
console.log(castArray(arr) === arr); // => true
// No arguments returns empty array
castArray(); // => []Converts any value to an array if it's not already one, with special handling for various input scenarios.
/**
* Casts value as an array if it's not one
* @param {*} [value] - The value to inspect
* @returns {Array} Returns the cast array
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return Array.isArray(value) ? value : [value];
}Behavior Details:
[][value]Usage Examples:
var castArray = require('lodash.castarray');
// Single value normalization
function processItems(items) {
// Ensure items is always an array
items = castArray(items);
return items.map(function(item) {
return item.toUpperCase();
});
}
processItems('hello'); // => ['HELLO']
processItems(['a', 'b']); // => ['A', 'B']
// API parameter normalization
function deleteUsers(userIds) {
userIds = castArray(userIds);
userIds.forEach(function(id) {
console.log('Deleting user:', id);
});
}
deleteUsers(123); // Works with single ID
deleteUsers([123, 456]); // Works with array of IDs
// Conditional array operations
function safePush(arr, items) {
items = castArray(items);
return arr.concat(items);
}
var myArray = [1, 2];
safePush(myArray, 3); // => [1, 2, 3]
safePush(myArray, [4, 5]); // => [1, 2, 4, 5]Array.isArray for optimal performanceThe castArray function is designed to never throw exceptions:
null and undefined