// EDIT:我正在使用Codeh解决此问题,它不使用过滤器或具有
function start(){
var gifts = ["book","car"];
var presents = ["game","book"];
var tim = new Set();
var sally = new Set();
tim.add(gifts);
sally.add(presents);
var ans = compare(tim,sally);
println(ans);
//should print in "book"
}
function compare(first,second){
//code here
}
我尝试遍历元素并使用并集
set.union();
。我不知道在哪里解决这个问题。谢谢!
答案 0 :(得分:1)
您可以使用filter()
和`has()过滤集合的内容。但是首先,您需要将数据正确地放入集合中。
(不幸的)这行不通:
tim.add(gifts);
因为它将整个数组添加为单个set元素。您只有在创建集合时才能这样做:
var tim = new Set(gifts);
function start(){
var gifts = ["book","car"];
var presents = ["game","book"];
var tim = new Set(gifts);
var sally = new Set(presents);
var ans = compare(tim,sally);
console.log(ans);
}
function compare(first,second){
return [...first].filter(item => second.has(item))
}
start()
答案 1 :(得分:1)
请注意,如果要查找两个集合的成员,则称为集合intersection,而不是集合union。
MDN包含各种设置操作的一些示例,包括交集:
var intersection = new Set([...set1].filter(x => set2.has(x)));
这是您如何在代码中使用它:
var compare = (a, b) => new Set([...a].filter(x => b.has(x)));
var gifts = new Set(["book", "car"]);
var presents = new Set(["game", "book"]);
var ans = compare(gifts, presents);
console.log(...ans);
答案 2 :(得分:1)
您可以获取第一个集合的项目数组,并通过Set本身采用Set
原型方法has
进行过滤。
基本上是这个
[...first].filter(Set.prototype.has, second)
^^^^^ the Set
^^^ take Set as iterable
^ ^ into array
^^^^^^ filter the array
^^^^^^^^^^^^^^^^^ by borrowing a method of Set
^^^^^^ with a Set
正在将集合first
转换为数组,并以thisArg
作为第二个参数的Array#filter
。
function compare(first, second) {
return [...first].filter(Set.prototype.has, second);
}
var gifts = ["book", "car"],
presents = ["game", "book"],
tim = new Set(gifts),
sally = new Set(presents);
console.log(compare(tim, sally));