使用 Javascript 数组计算集差的最快或最优雅的方法是什么? [英] What is the fastest or most elegant way to compute a set difference using Javascript arrays?

查看:36
本文介绍了使用 Javascript 数组计算集差的最快或最优雅的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AB为两组.我正在寻找真的快速或优雅的方法来计算集差(A - BA \B,取决于您的偏好)它们之间.正如标题所说,这两个集合作为 Javascript 数组进行存储和操作.

Let A and B be two sets. I'm looking for really fast or elegant ways to compute the set difference (A - B or A \B, depending on your preference) between them. The two sets are stored and manipulated as Javascript arrays, as the title says.

注意事项:

  • Gecko 特有的技巧没问题
  • 我更愿意坚持使用本机函数(但如果速度更快,我愿意使用轻量级库)
  • 我见过但没有测试过JS.Set(见上一点)
  • Gecko-specific tricks are okay
  • I'd prefer sticking to native functions (but I am open to a lightweight library if it's way faster)
  • I've seen, but not tested, JS.Set (see previous point)

我注意到关于包含重复元素的集合的评论.当我说设置"时,我指的是数学定义,这意味着(除其他外)它们不包含重复元素.

I noticed a comment about sets containing duplicate elements. When I say "set" I'm referring to the mathematical definition, which means (among other things) that they do not contain duplicate elements.

推荐答案

如果不知道这个是不是最有效,但可能是最短的

if don't know if this is most effective, but perhaps the shortest

A = [1, 2, 3, 4];
B = [1, 3, 4, 7];

diff = A.filter(function(x) { return B.indexOf(x) < 0 })

console.log(diff);

更新到 ES6:

A = [1, 2, 3, 4];
B = [1, 3, 4, 7];

diff = A.filter(x => !B.includes(x) );

console.log(diff);

这篇关于使用 Javascript 数组计算集差的最快或最优雅的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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