简体   繁体   English

Javascript:多个数组循环

[英]Javascript: Multiple Array looping

TL DR; TL DR; What is the most efficient way to sort and compare values in a multiple arrays? 在多个数组中排序和比较值的最有效方法是什么?

Okay, so we'll assume a few constants to make this whole thing simple var a = [1, 2, 3, 4, 5, 6], b = [0, 9, 8, 7, 6, 88, 99, 77], i, j; 好的,所以我们假设一些常数使整个事情变得简单var a = [1,2,3,4,5,6],b = [0,9,8,7,6,88,99, 77],我,j;

Now if I wanted to see if any value in a is equal to any other value in b I'd have to sort through one of these arrays 6 times. 现在,如果我想查看a中的任何值是否等于b中的任何其他值,我必须对这些数组中的一个进行6次排序。 That's a lot of work, and it would seem there should be a more efficient way to do this. 这是很多工作,似乎应该有一种更有效的方法来做到这一点。 For those needing a visual aide here you are ( and yes I know about -- and ++ I just don't like to use 'em ): 对于那些需要视觉助手的人来说,你是(而且我知道 - 而++我只是不喜欢使用'em):

for (i = a.length - 1; i > -1; i -= 1) {
    for (j = b.length - 1; j > -1; j -= 1) {
        if (a[i] === b[j]) {
            return b[j];
        }
    }
}

The B array gets ran through once for EACH element in A. Again, certainly there is a more efficient way to complete this task? 对于A中的EACH元素,B数组会运行一次。同样,当然有更有效的方法来完成此任务吗?

-Akidi -Akidi

Depends on the size of your input arrays (several tradeoffs there)-- your nested loops are simplest for small inputs like your examples. 取决于输入数组的大小(那里有几个权衡) - 你的嵌套循环对于像你的例子这样的小输入是最简单的。

If you have huge arrays, and have control over their construction, consider keeping a map (Object in JS) around acting as a lookup set (if you're creating a in a loop anyways, you can build the set in parallel.) 如果你有庞大的阵列,并有超过他们的施工控制,可以考虑保持地图(JS对象)周围充当查找集(如果您要创建a在一个循环不管怎么说,你可以建立并行设置的。)

var setA = {};
for (int i = 0; i < a.length; i++) {
    setA[a[i]] = true;
}

Then you can see whether something exists in the set by just checking setA[ ? 然后你可以通过检查setA[ ?]来查看集合中是否存在某些东西。 ] . ]

Likewise with B, or with both together, etc, depending on your needs. 同样与B,或两者一起等,取决于您的需求。

Maybe something like this may help? 也许这样的事可能会有所帮助?

var a = [1, 2, 3, 9, 5, 0], b = [0, 9, 8, 7, 6, 88, 99, 77];
var a_dict = {}, l = a.length;

for (var i=0; i < l; i++) {
  a_dict[a[i]] = 1;
}

l = b.length;
for (var i=0; i < l; i++) {
  if(!!a_dict[b[i]]){
    console.log(b[i]);
  }
}

You can convert one array to "dict-like" object and compare others with it... 您可以将一个数组转换为“类似dict”的对象,并将其他数组与其进行比较......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM