How to use the castArray function from lodash

Find comprehensive JavaScript lodash.castArray code examples handpicked from public code repositorys.

lodash.castArray is a utility function in the Lodash library that converts the given value into an array.

43
44
45
46
47
48
49
50
51
52
module.exports.bitwiseXor          = _.bitwiseXor;
module.exports.bitwiseZ            = _.bitwiseZ;
module.exports.bound               = _.bound;
module.exports.camelCase           = _.camelCase;
module.exports.capitalize          = _.capitalize;
module.exports.castArray           = _.castArray;
module.exports.cat                 = _.cat;
module.exports.ceil                = _.ceil;
module.exports.chain               = _.chain;
module.exports.chunk               = _.chunk;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

362
363
364
365
366
367
368
369
370
371
372
373
374
375
console.log(wrap(1)); // => 4




// Lang


const castArray = _.castArray(1);
console.log(castArray); // => [1]


const clone = _.clone({ 'a': 1 });
console.log(clone); // => { 'a': 1 }
fork icon0
star icon4
watch icon0

+ 15 other calls in file

How does lodash.castArray work?

lodash.castArray is a function that creates an array from the given value, if the value is not an array, it will return an array with the original value as the single element of the array.

296
297
298
299
300
301
302
303
304
305
emptyArray: give$([]),
emptyObject: give$({}),
string: (arg) => arg.toString(),
boolean: (arg) => !!arg,
number: (arg) => Number(arg),
array: (arg) => _.castArray(arg),
keys: (arg) => _.keys(arg),
json: (arg) => JSON.stringify(arg),
yaml: (arg) => yaml.dump(arg),
parsedJson: (arg) => JSON.parse(arg),
fork icon0
star icon0
watch icon1

+ 2 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
const castedArray = _.castArray("hello");
console.log(castedArray); // ['hello']

const array = ["hello", "world"];
const castedArray2 = _.castArray(array);
console.log(castedArray2 === array); // true

const nullValue = null;
const castedArray3 = _.castArray(nullValue);
console.log(castedArray3); // [null]

In the first example, lodash.castArray is called with a string as its argument. Since it is not an array, it is wrapped in a new array and returned. In the second example, an array is passed to lodash.castArray. Since it is already an array, it is returned without modification. In the third example, lodash.castArray is called with null as its argument. Since null is not an array, it is wrapped in a new array and returned.

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)