Lodash _.cat() Method
Last Updated :
14 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.cat() method is used to concatenate zero or more arguments into one array. It can be used to concatenate multiple types of arguments,
Syntax:
_.cat( arg1, arg2, ..., argn )
Parameters:
- args: This method accepts multiple arguments to concatenate into a single array.
Return Value: This method returns a concatenated array.
Note: This method will not work in normal JavaScript because it requires the Lodash contrib library to be installed. The lodash-contrib library can be installed using npm install lodash-contrib –save
Example 1: In this example, we will concatenate 2 arrays.
Javascript
var _ = require( 'lodash-contrib' );
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr = _.cat(arr1, arr2);
console.log( "array 1 : " + arr1);
console.log( "array 2 : " + arr2);
console.log( "concatenated array : " + arr);
|
Output:
array 1 : 1,2,3
array 2 : 4,5,6
concatenated array : 1,2,3,4,5,6
Example 2: In this example, we will concatenate 2 numbers to form an array.
Javascript
var _ = require( 'lodash-contrib' );
var num1 = 1;
var num2 = 4;
var arr = _.cat(num1, num2);
console.log( "num1 : " + num1);
console.log( "num2 : " + num2);
console.log( "Concatenated array : " + arr);
|
Output:
num1 : 1
num2 : 4
Concatenated array : 1,4
Example 3: In this example, we will concatenate 3 arrays.
Javascript
var _ = require( 'lodash-contrib' );
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var arr = _.cat(arr1, arr2, arr3);
console.log( "array 1 : " + arr1);
console.log( "array 2 : " + arr2);
console.log( "array 3 : " + arr3);
console.log( "Concatenated array : " + arr);
|
Output:
array 1 : 1,2,3
array 2 : 4,5,6
array 3 : 7,8,9
Concatenated array : 1,2,3,4,5,6,7,8,9
Example 4: The _.cat() function will also work with the arguments object as if it were an array.
Javascript
var _ = require( 'lodash-contrib' );
function f(){
return _.cat(arguments, 4,5,6);
}
console.log( "Array is : " + f(1,2,3));
|
Output:
Array is : 1,2,3,4,5,6
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...