Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.intersectionBy() is used to take the intersection of the a array with any number of arrays based on some function that iterates over each element of the array. It returns the array after doing 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 intersection with no duplicates.
Note: Please install lodash module by npm install lodash
before using the below given code.
Example 1: When Iteratee function is not given it behaves same as intersection() function of the lodash.
javascript
// 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: When Math.ceil() function is used to runs over array1 and all value of array1 are compare to next nearest larger integer and then intersection is taken.
javascript
// 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 = lodash.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: When multiple common elements are present it return them only one times and no duplicates are returned in the array.
javascript
// 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 = lodash.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: