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.
// Requiring the lodash library const _ = require( "lodash" );
// Original arrays let array1 = [1, 2, 4, 3, 4, 4] let array2 = [1, 2, 5, 6] // Using _.intersectionBy() method let newArray = _.intersectionBy(array1, array2); // Printing original Array console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
// Printing the newArray after intersection 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.
// Requiring the lodash library const _ = require( "lodash" );
// Original array and array1 // float values are given let array1 = [1.1, 2.6, 4, 3.2, 1, 2] let array2 = [1, 2, 3, 5, 6] // Using _.intersection() method // when this function is run array1 // looks like array1=[2, 3, 4, 4, 1, 2] // after that intersection is taken let newArray = _.intersectionBy( array1, array2, Math.ceil);
// Printing original Array console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
// Printing the newArray 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.
// Requiring the lodash library const _ = require( "lodash" );
// Original array let array1 = [ "a" , "b" , "c" , "a" ]
let array2 = [ "a" , "d" , "e" , "a" ]
// Using _.intersection() method let newArray = _.intersectionBy( array1, array2, "a" );
// Printing original Array console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
// Printing the newArray console.log( "new Array: " , newArray)
|
Output: