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.
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.
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 [...
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.
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.
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);
why not use reduce ?
_.reduce(selected,function(result,a){ return _.intersection(result,a); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With