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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
function f() { return _.cons(0, arguments) }
console.log("Constructed array : ");
console.log(f(1, 2, 3));

chevron_right


Output:

Constructed array :
[ 0, 1, 2, 3 ]

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.