Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform union or intersection on an array of arrays with Underscore.js

I have an array of arrays:

var selected = [[1, 4, 5, 6], [1, 2, 3, 5, 7], [1, 4, 5, 6], [1, 7]]; 

Underscore.js has convenient union and intersection methods but they work on passing each array individually as arguments.

How would I go about it if the number of arrays on which the set operations are to be performed is arbitrary?

This question addresses something similar but it is for an array containing objects.

like image 794
Nandeep Mali Avatar asked Apr 26 '13 05:04

Nandeep Mali


People also ask

What is _ each in Javascript?

The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.

How do you Union an array?

To get a union of two arrays:const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; function getUnion(array1, array2) { const difference = array1. filter( element => ! array2. includes(element) ); return [...

How do you use underscore in Javascript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

How do you use intersection in Javascript?

Example 1: Perform Intersection Using SetThe for...of loop is used to iterate over the second Set elements. The has() method is used to check if the element is in the first Set . If the element is present in the first Set , that element is added to the intersectionResult array using the push() method.


2 Answers

One can use apply to pass an arbitrary number of arguments to a method.

For union:

// Outputs [1, 4, 5, 6, 2, 3, 7] var selectedUnion = _.union.apply(_, selected); 

For intersection:

// Outputs [1] var selectedIntersection = _.intersection.apply(_, selected); 
like image 78
Nandeep Mali Avatar answered Oct 01 '22 02:10

Nandeep Mali


why not use reduce ?

_.reduce(selected,function(result,a){     return _.intersection(result,a); }); 
like image 30
Aladdin Mhemed Avatar answered Oct 01 '22 03:10

Aladdin Mhemed