Underscore.js _.cons() Method
Last Updated :
05 Apr, 2023
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
const _ = require( 'underscore-contrib' );
let element = 0
let arr2 = [4, 5, 5]
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
const _ = require( 'underscore-contrib' );
let arr1 = [0]
let arr2 = [4, 5, 5]
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
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 ]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...