Skip to content
Related Articles

Related Articles

Improve Article

Underscore.js _.cons() Method

  • Last Updated : 23 Jul, 2020

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 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.




// Defining underscore contrib variable
var _ = require('underscore-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 underscore contrib variable
var _ = require('underscore-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 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.




// Defining underscore contrib variable
var _ = 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 ]



My Personal Notes arrow_drop_up
Recommended Articles
Page :