Lodash _.intersectionBy() Method with Examples

In this blog, we will see how to use Lodash’s _.intersectionBy() method in JavaScript. Lodash is a JavaScript library and we have used it in many of our previous blogs. It works on the top of underscore.js and it is used in working with arrays, strings, objects, numbers etc. Lodash is capable of simplfying many complex logic.

The method which is discussed in this tutorial is used to take the intersection of the array with any number of arrays depending upon some function that iterates over each element present in the array. The Array is returned after completing the intersection of arrays.

Syntax for IntersectionBy Method

_.intersectionBy([arrays], [iteratee=_.identity])

The Parameters used here has a purpose and those are as follows:

  • Arrays : It’s array whose intersection has to be taken
  • iteratee=._identity : the function that iterates over all the elements of the array

Lodash – IntersectionBy Examples

Let’s see the code now:

Example 1

// 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 the newArray after intersection
console.log("new Array: ", newArray);

Output

new array: [1, 2]

Example 2

// 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 the newArray
console.log("new Array: ", newArray);

Output

new array: [1.1, 2.6, 1]

That’s it for the blog. Hope the content provided here was informative and you understood the code well. Comment below your doubts and queries.

Leave a Comment