Open In App

Lodash _.intersectionWith() Method

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • arrays: It takes an array as a parameter.
  • comparator: It is the function that iterates over each value of the array and compares the values with the given comparator function.

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.

Javascript




// 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.

Javascript




// 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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads