Friday, September 27, 2024
Google search engine
HomeLanguagesJavascriptLodash _.intersectionWith() Method

Lodash _.intersectionWith() Method

Lodash is a JavaScript library that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.
The _.intersectionwith() method is used to take the intersection of the one or more arrays. It is 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])

Parameter: This method accepts two parameters as mention above and describe below:

  • 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 intersection of arrays.

Note: Please install lodash module by using command npm install lodash before using the code given below. 

Example 1: 

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

RELATED ARTICLES

Most Popular

Recent Comments