Lodash _.intersectionWith() Method
Last Updated :
31 Oct, 2023
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
const _ = require( "lodash" );
let array1 = [
{ "a" : 1 }, { "b" : 2 },
{ "b" : 2, "a" : 1 }
]
let array2 = [
{ "a" : 1, "b" : 2 },
{ "a" : 1 }
]
let newArray = _.intersectionWith(
array1, array2, _.isEqual);
console.log( "original Array1: " , array1)
console.log( "original Array2: " , array2)
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
const _ = require( "lodash" );
let array1 = [
{ "a" : 1 }, { "b" : 2 },
{ "b" : 2, "a" : 1 }
]
let array2 = [
{ "a" : 1, "b" : 2 },
{ "a" : 1 }
]
let newArray = _.intersectionWith(
array1, array2);
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...