Javascript:设置数据结构:相交 [英] Javascript: Set Data Structure: intersect

查看:129
本文介绍了Javascript:设置数据结构:相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试让两个数据集相交但我无法做到:(例如,在我的代码中,相交mySet和mySet2应该产生1,因为它们的值都为1设置。

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和Set 2都有1但我的功能( intersection_destructive)不会返回它。我不确定如何交叉它们,我搜索了stackoverflow并找到了intersection_destructive,但它对我不起作用,我也尝试过:

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
});

按此:最简单的javascript中的数组交集代码

但我在过滤器上收到错误当我尝试运行它时。

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

推荐答案

要获得交集,您可以迭代集合中的项目并检查它们是否属于到另一个:

To get the intersection, you can iterate the items of a set and check if they belong to the other one:

var intersect = new Set();
for(var x of mySet1) if(mySet2.has(x)) intersect.add(x);

在ES7中,您可以使用 array comprehensions generator comprehensions

In ES7 you can simplify it with array comprehensions or generator comprehensions:

var intersect = new Set((for (x of mySet1) if (mySet2.has(x)) x));

这篇关于Javascript:设置数据结构:相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆