Open In App

Lodash _.intersectionWith() Method

Lodash _.intersectionwith() method is used to take the intersection of one or more arrays. It is the same as the intersection function in lodash only difference is that it accepts a comparator which is invoked to compare elements of arrays.

Syntax:

intersectionWith([arrays], [comparator]);

Parameters:

Return Value:

It returns the array after the intersection of arrays.



Example 1: In this example, we are printing the intersection of the two arrays by the use of the lodash _.intersectionWith() method and passing the _.isEqual() method to it.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [
    { "a": 1 }, { "b": 2 },
    { "b": 2, "a": 1 }
]
 
let array2 = [
    { "a": 1, "b": 2 },
    { "a": 1 }
]
 
// Using _.intersectionWith() method
let newArray = _.intersectionWith(
    array1, array2, _.isEqual);
 
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
 
// Printing the newArray
console.log("new Array: ", newArray)

Output:



Example 2: In this example, we are printing the intersection of the two arrays by the use of the lodash _.intersectionWith() method and not using comparator function i.e. _.isequal() then output is empty array.




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let array1 = [
    { "a": 1 }, { "b": 2 },
    { "b": 2, "a": 1 }
]
 
let array2 = [
    { "a": 1, "b": 2 },
    { "a": 1 }
]
 
// Using _.intersectionWith() method
// and no comparator function
let newArray = _.intersectionWith(
    array1, array2);
 
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
 
// Printing the newArray
console.log("new Array: ", newArray)

Output:


Article Tags :