0
# Lodash CastArray
1
2
Lodash 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.
3
4
## Package Information
5
6
- **Package Name**: lodash.castarray
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.castarray`
10
11
## Core Imports
12
13
```javascript
14
var castArray = require('lodash.castarray');
15
```
16
17
For ES modules (if using a bundler):
18
19
```javascript
20
import castArray from 'lodash.castarray';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var castArray = require('lodash.castarray');
27
28
// Convert single values to arrays
29
castArray(1); // => [1]
30
castArray('hello'); // => ['hello']
31
castArray({ a: 1 }); // => [{ a: 1 }]
32
castArray(null); // => [null]
33
castArray(undefined); // => [undefined]
34
35
// Arrays are returned unchanged (reference preserved)
36
var arr = [1, 2, 3];
37
console.log(castArray(arr) === arr); // => true
38
39
// No arguments returns empty array
40
castArray(); // => []
41
```
42
43
## Capabilities
44
45
### Array Conversion
46
47
Converts any value to an array if it's not already one, with special handling for various input scenarios.
48
49
```javascript { .api }
50
/**
51
* Casts value as an array if it's not one
52
* @param {*} [value] - The value to inspect
53
* @returns {Array} Returns the cast array
54
*/
55
function castArray() {
56
if (!arguments.length) {
57
return [];
58
}
59
var value = arguments[0];
60
return Array.isArray(value) ? value : [value];
61
}
62
```
63
64
**Behavior Details:**
65
66
- **No arguments**: Returns empty array `[]`
67
- **Array input**: Returns the original array unchanged (maintains reference equality)
68
- **Non-array input**: Wraps the value in a new array `[value]`
69
- **All types supported**: Handles strings, numbers, objects, null, undefined, functions, etc.
70
- **No exceptions**: Never throws errors, handles all input gracefully
71
72
**Usage Examples:**
73
74
```javascript
75
var castArray = require('lodash.castarray');
76
77
// Single value normalization
78
function processItems(items) {
79
// Ensure items is always an array
80
items = castArray(items);
81
return items.map(function(item) {
82
return item.toUpperCase();
83
});
84
}
85
86
processItems('hello'); // => ['HELLO']
87
processItems(['a', 'b']); // => ['A', 'B']
88
89
// API parameter normalization
90
function deleteUsers(userIds) {
91
userIds = castArray(userIds);
92
userIds.forEach(function(id) {
93
console.log('Deleting user:', id);
94
});
95
}
96
97
deleteUsers(123); // Works with single ID
98
deleteUsers([123, 456]); // Works with array of IDs
99
100
// Conditional array operations
101
function safePush(arr, items) {
102
items = castArray(items);
103
return arr.concat(items);
104
}
105
106
var myArray = [1, 2];
107
safePush(myArray, 3); // => [1, 2, 3]
108
safePush(myArray, [4, 5]); // => [1, 2, 4, 5]
109
```
110
111
## Performance Characteristics
112
113
- **Minimal overhead**: Single condition check plus array creation when needed
114
- **Reference preservation**: Array inputs return the same reference (no copying)
115
- **Native type checking**: Uses `Array.isArray` for optimal performance
116
- **No iterations**: Constant time operation regardless of input size
117
118
## Error Handling
119
120
The `castArray` function is designed to never throw exceptions:
121
122
- Accepts any number of arguments (uses only the first)
123
- Handles all JavaScript types including `null` and `undefined`
124
- No validation or type checking that could cause errors
125
- Defensive programming approach with predictable fallback behavior