Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Set Data Structure: intersect

Trying to get two data sets to intersect but I can't do it :(. For example, in my code below, intersecting mySet and mySet2 should yield "1" since they both have a value of "1" in their set.

var mySet = new Set();
var mySet2=new Set();
mySet.add(1);
mySet.add(2);
mySet.add("HELLOOOOO");
mySet2.add("hi");
mySet2.add(1);


var a = Array(mySet, mySet2);
console.log(a);

mySet.forEach(function(value) {
    console.log(value);
});


mySet2.forEach(function(value) {
    console.log(value);
});

function intersection_destructive(a, b)
{
    var result = new Array();
    while( mySet.length > 0 && mySet2.length > 0 )
    {
        if      (mySet[0] < mySet2[0] ){ mySet.shift(); }
        else if (mySet[0] > mySet2[0] ){ mySet2.shift(); }
        else /* they're equal */
        {
            result.push(mySet.shift());
            mySet2.shift();
        }
    }

    return result;
}

Set 1 and Set 2 both have "1" in it but my function (intersection_destructive) doesn't return it. I'm not sure how to intersect them, I searched stackoverflow and found intersection_destructive but it didn't work for me, I also tried:

array1.filter(function(n) {
    return array2.indexOf(n) != -1
});

as per this: Simplest code for array intersection in javascript

but I get an error on "filter" when I try to run it.

like image 691
Snorlax Avatar asked Aug 10 '15 23:08

Snorlax


People also ask

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.

Is Set Has faster than array includes?

Adding elements to a collectionpush array method is about 4 times faster than the . add set method, no matter the number of elements being added.

Does JavaScript Set preserve order?

Randomly experimenting with JavaScript (ES6) and reading its documentation I found out that Set maintains the insertion order of its elements.

Can I use Set JavaScript?

You can create a JavaScript Set by: Passing an Array to new Set() Create a new Set and use add() to add values. Create a new Set and use add() to add variables.


1 Answers

Sadly as you've figured out there's no native intersection or union operations. It's not terribly complex to find the intersection though:

let a = new Set([1,2,3])
let b = new Set([1,2,4])
let intersect = new Set([...a].filter(i => b.has(i)));
like image 192
Kit Sunde Avatar answered Oct 06 '22 16:10

Kit Sunde