Lodash | _.castArray() Method

The _.castArray() method is used to cast value into an array if it is not an array.

Syntax:

_.castArray( value )

Parameters: This method accepts single parameter as mentioned above and described below:

  • value: This parameter holds the value that need to be inspect.

Return Value: It returns an array with the including value passed in the _.castArray().

Example 1: This example using integer value as a parameter.



filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = 10;
  
let arr = _.castArray(x);
  
console.log("\n\nThe value returned to by _castArray(x) is", arr);

chevron_right


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

Example 2: This example using String, null, and undefined as a parameter.

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = _.castArray('abc');
  
console.log('\n With String ', x );
   
let y = _.castArray(null);
  
console.log('\n With null ', y );
   
let z = _.castArray(undefined);
  
console.log('\n With undefined ', z);

chevron_right


Output:

Example 3: With no parameter, object, and function.

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = _.castArray();
  
console.log("\n With no parameter ", x);
  
let y = _.castArray({"name":"lodash",
         "work":"I'm make js more" });
  
console.log("\n With object ", y);
  
let z = _.castArray(function hello() {
    console.log("hello");
});
  
console.log("\n with function ", z);

chevron_right


Output:

Eample 4: This example using multiple parameters, it will take only the first parameter and with an array, it will just return the same array.

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let x = _.castArray(1, 2, "hello");
  
console.log('\n With multiple paramter ', x);
  
let y = _.castArray([1, 2, 3]);
  
console.log('\n With array ', y);

chevron_right


Output:

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#castArray

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.