The Lodash _.cons() Method is used to construct a new array by taking some element and putting it at the front of another array or element.
Syntax:
_.cons(element, Array_or_element);
Parameters:
- element: It is the element that gets put in the front to construct a new Array.
- Array_or_element: It is the second parameter used to construct an array.
Return Value: This method returns a newly constructed array.
Note: This will not work in normal JavaScript because it requires the Lodash contrib library to be installed.
Lodash contrib library can be installed using npm install lodash-contrib –save
Example 1: In this example, we will simply construct a new array by just putting an element in front using this method.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' );
// Element var element = 0
// Array var arr2 = [4,5,5]
// Constructing array carr = _.cons(element, arr2); console.log( "element : " );
console.log(element); console.log( "array2 : " );
console.log(arr2); console.log( "Constructed array : " );
console.log(carr); |
Output:
element : 0 array2 : [ 4, 5, 5 ] Constructed array : [ 0, 4, 5, 5 ]
Example 2: This element also takes an array as the first argument.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' );
// Array1 var arr1 = [0]
// Array2 var arr2 = [4,5,5]
// Constructing array carr = _.cons(arr1, arr2); console.log( "Array1 : " );
console.log(arr1); console.log( "Array2 : " );
console.log(arr2); console.log( "Constructed array : " );
console.log(carr); |
Output: The first array takes place as a sub array in this example
element : [ 0 ] array2 : [ 4, 5, 5 ] Constructed array : [ [ 0 ], 4, 5, 5 ]
Example 3: In this example, we will construct a new array using arguments.
// Defining lodash contrib variable var _ = require( 'lodash-contrib' );
function f() { return _.cons(0, arguments) }
console.log( "Constructed array : " );
console.log(f(1,2,3)); |
Output:
Constructed array : [ 0, 1, 2, 3 ]