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.
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 underscore.js contrib library to be installed.
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.
javascript
// Defining underscore contrib variable const _ = require( 'underscore-contrib' ); // Element let element = 0 // Array let 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.
javascript
// Defining underscore contrib variable const _ = require( 'underscore-contrib' ); // Array1 let arr1 = [0] // Array2 let 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 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.
javascript
// Defining underscore contrib variable const _ = require( 'underscore-contrib' ); function f() { return _.cons(0, arguments) } console.log( "Constructed array : " ); console.log(f(1, 2, 3)); |
Output:
Constructed array : [ 0, 1, 2, 3 ]
Contact Us