Lodash _.intersectionBy() Method
Last Updated :
31 Oct, 2023
Lodash _.intersectionBy() is used to take the intersection of the array with any number of arrays based on some function that iterates over each element of the array. It returns the array after doing the intersection of the arrays.
Syntax:
_.intersectionBy([arrays], [iteratee=_.identity]);
Parameters:
- arrays: It is the array whose intersection has to be taken.
- iteratee=_.identity: It is the function that iterates over each element of the array whose intersection is to be taken.
Return Value:
It returns the array after the intersection with no duplicates.
Example 1: In this example, we are getting the intersection of two arrays by the use of the lodash _.intersectionBy() method.
javascript
const _ = require( "lodash" );
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = [1, 2, 5, 6]
let newArray = _.intersectionBy(array1, array2);
console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
console.log( "new Array: " , newArray)
|
Output:
Example 2: In this example, we are getting the intersection of two arrays and also printing those values only which are closer to Math.ceil by the use of the lodash _.intersectionBy() method.
javascript
const _ = require( "lodash" );
let array1 = [1.1, 2.6, 4, 3.2, 1, 2]
let array2 = [1, 2, 3, 5, 6]
let newArray = _.intersectionBy(
array1, array2, Math.ceil);
console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
console.log( "new Array: " , newArray)
|
Output:
Example 3: In this example, we are getting the intersection of two arrays by the use of the lodash _.intersectionBy() method. When multiple common elements are present it return them only one times and no duplicates are returned in the array.
javascript
const _ = require( "lodash" );
let array1 = [ "a" , "b" , "c" , "a" ]
let array2 = [ "a" , "d" , "e" , "a" ]
let newArray = _.intersectionBy(
array1, array2, "a" );
console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
console.log( "new Array: " , newArray)
|
Output:
Share your thoughts in the comments
Please Login to comment...