Underscore.js _.cons() Method
The _.cons() Method is used to construct a new array by taking some element and putting it at the front of another array or element.
- 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 array.
Return Value: This method returns a newly constructed array.
underscore.js contrib library can be installed using npm install underscore-contrib –save
Example 1: In this example, we will simply construct a new array by just putting an element in front using this method.
element : 0 array2 : [ 4, 5, 5 ] Constructed array : [ 0, 4, 5, 5 ]
Example 2: This element also takes an array as the first argument.
Output: The first array takes place as a subarray 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.
Constructed array : [ 0, 1, 2, 3 ]