如何编写非残酷搜索

时间:2017-02-25 20:53:58

标签: javascript arrays

我编写了一个搜索两个数组之间匹配的javascript代码段。我知道如何粗暴地搜索它(数组需要一个数字输入,搜索其他数组的每个值以查看它们是否匹配一遍又一遍地执行此操作),但效率非常低。如果有人知道在两个阵列之间搜索公共值的方法,以便花费最少的时间,请帮助我。

var 1 = ["bob", "Sophie"];
var 2 = ["Sherry", "Gerard", "Joseph"];

for(var i; i <= 1.length; i++){

switch(1[i]){

case 1[i] === 2[1]:
console.log("They match!");

break;

case 1[i] === 2[2]:
console.log("They match!");

break;

case 1[i] === 2[3]:
console.log("They match!");

break;

case default:
console.log("No matches found.");

}
}
}

PS Don介意语法错误,这是一个&#34;粗略草案&#34;的代码。我这么说就是为了让你能看出我的意思。

2 个答案:

答案 0 :(得分:1)

你可以使用哈希表并迭代第一个数组来创建一个表,然后只用一个循环过滤第二个数组。

Complexity:O(n + m)

var array1 = ["bob", "Sophie"],
    array2 = ["Sherry", "Gerard", "Joseph"],
    hash = Object.create(null),
    found;

array1.forEach(function (a) {
    hash[a] = true;
});

found = array2.filter(function (a) {
    return hash[a];
});
console.log(found);

array2.push("Sophie");
found = array2.filter(function (a) {
    return hash[a];
});
console.log(found);

ES6与Set

var array1 = ["bob", "Sophie"],
    array2 = ["Sherry", "Gerard", "Joseph"],
    aSet = new Set(array1),
    found;

found = array2.filter(a => aSet.has(a));
console.log(found);

array2.push("Sophie");
found = array2.filter(a => aSet.has(a));
console.log(found);

答案 1 :(得分:0)

如果我理解正确,你需要找到共同的元素。然后我将使用Underscore.Js外部库(如下面的代码片段所示)或者在以下链接中提供其他解决方案 How to find common elements only between 2 arrays in jquery

&#13;
&#13;
var array1 = ["bob", "Sophie"];
var array2 = ["bob", "Gerard", "Joseph"];

alert(_.intersection(array1, array2));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;