ArticleZip > How To Perform Union Or Intersection On An Array Of Arrays With Underscore Js

How To Perform Union Or Intersection On An Array Of Arrays With Underscore Js

Arrays are a fundamental part of coding, but sometimes working with arrays of arrays can be a bit tricky. Don't worry, we've got you covered. In this article, we'll dive into how you can perform union or intersection on an array of arrays using Underscore.js.

First things first, let's clarify what we mean by union and intersection. Union is the operation that combines all the unique elements from different arrays into a single array. On the other hand, intersection involves finding the common elements between two or more arrays.

Underscore.js is a popular JavaScript library that provides a wide range of useful functions to enhance your coding experience. To start performing union or intersection on an array of arrays, you'll need to have Underscore.js added to your project. If you haven't already done this, you can easily include it by adding the following script tag to your HTML file:

Html

Once you have Underscore.js set up, let's move on to the fun part - performing union or intersection. To perform the union operation, you can use the `_.union()` function provided by Underscore.js. This function takes multiple arrays as arguments and returns a new array containing all the unique elements from those arrays. Here's an example to illustrate how you can use `_.union()`:

Javascript

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const array3 = [3, 4, 5];

const unionResult = _.union(array1, array2, array3);
console.log(unionResult);

In this example, `unionResult` will contain `[1, 2, 3, 4, 5]` since it combines all the unique elements from the three arrays.

Moving on to the intersection operation, Underscore.js provides the `_.intersection()` function that does the job for you. This function takes multiple arrays as arguments and returns a new array containing the common elements across those arrays. Here's an example to demonstrate how you can use `_.intersection()`:

Javascript

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const array3 = [3, 4, 5];

const intersectionResult = _.intersection(array1, array2, array3);
console.log(intersectionResult);

In this case, `intersectionResult` will be `[3]` since it extracts the common element present in all three arrays.

We hope this article has shed some light on how to perform union or intersection on an array of arrays using Underscore.js. With these handy functions at your disposal, manipulating arrays in your code will be a breeze. Happy coding!