Javascript 如何在两个数组中找到匹配的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12433604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find matching values in two arrays?
提问by Mr. 1.0
I have two arrays, and I want to be able to compare the two and only return the values that match. For example both arrays have the value cat
so that is what will be returned. I haven't found anything like this. What would be the best way to return similarities?
我有两个数组,我希望能够比较两者并只返回匹配的值。例如,两个数组都具有值,cat
因此将返回该值。我没有找到这样的东西。返回相似性的最佳方法是什么?
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
//if value in array1 is equal to value in array2 then return match: cat
采纳答案by jeremy
Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1
, then push
it onto the returned array.
当然,我的方法是遍历第一个数组一次并检查第二个数组中每个值的索引。如果索引为> -1
,则将push
其添加到返回的数组中。
?Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
?
My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in
, you can sort both arrays first to reindex all their values:
? 我的解决方案不像其他人那样使用两个循环,因此它可能运行得更快一些。如果您想避免使用for..in
,您可以先对两个数组进行排序以重新索引它们的所有值:
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
Usage would look like:
用法如下:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
如果您在扩展 Array 原型时遇到问题,可以轻松地将其更改为函数。
var diff = function(arr, arr2) {
And you'd change anywhere where the func originally said this
to arr2
.
并且其中FUNC原本说你随时随地更改this
到arr2
。
回答by jota3
You can use :
您可以使用 :
const intersection = array1.filter(element => array2.includes(element));
回答by Fred Read
I found a slight alteration on what @jota3 suggested worked perfectly for me.
我发现@jota3 建议的内容略有改动,对我来说非常有效。
var intersections = array1.filter(e => array2.indexOf(e) !== -1);
Hope this helps!
希望这可以帮助!
回答by phant0m
This function runs in O(n log(n) + m log(m))
compared to O(n*m)
(as seen in the other solutions with loops/indexOf
) which can be useful if you are dealing with lots of values.
O(n log(n) + m log(m))
与O(n*m)
(如在其他带有 loops/ 的解决方案中所见)相比,此函数运行,这在indexOf
您处理大量值时非常有用。
However, because neither "a" > 1
nor "a" < 1
, this only works for elements of the same type.
但是,因为既不是"a" > 1
也不是"a" < 1
,这仅适用于相同类型的元素。
function intersect_arrays(a, b) {
var sorted_a = a.concat().sort();
var sorted_b = b.concat().sort();
var common = [];
var a_i = 0;
var b_i = 0;
while (a_i < a.length
&& b_i < b.length)
{
if (sorted_a[a_i] === sorted_b[b_i]) {
common.push(sorted_a[a_i]);
a_i++;
b_i++;
}
else if(sorted_a[a_i] < sorted_b[b_i]) {
a_i++;
}
else {
b_i++;
}
}
return common;
}
Example:
例子:
var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
intersect_arrays(array1, array2);
>> ["cat", "hut"]
回答by 0x499602D2
Loop through the second array each time you iterate over an element in the first array, then check for matches.
每次迭代第一个数组中的元素时循环遍历第二个数组,然后检查匹配项。
var array1 = ["cat", "sum", "fun", "run"],
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) matches.push( a[i] );
}
}
return matches;
}
getMatch(array1, array2); // ["cat"]
回答by hardik beladiya
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array3 = array2.filter(function(obj) {
return array1.indexOf(obj) == -1;
});
回答by Irfandy Jip
You can use javascript function .find()
As it says in MDN, it will return the first valuethat is true. If such an element is found, find immediatelyreturns the value of that element. Otherwise, find returns undefined
.
您可以使用 javascript 函数,.find()
正如 MDN 中所说,它将返回第一个为真的值。如果找到这样的元素, find立即返回该元素的值。否则, find 返回undefined
。
var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
found = array1.find( val => array2.includes(val) )
console.log(found)
回答by leojh
Libraries like underscore and lodash have a utility method called intersection
to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection
像 underscore 和 lodash 这样的库有一个实用方法调用intersection
来在传入的数组中查找匹配项。看看:http: //underscorejs.org/#intersection
回答by ddobby94
With some ES6:
使用一些 ES6:
let sortedArray = [];
firstArr.map((first) => {
sortedArray[defaultArray.findIndex(def => def === first)] = first;
});
sortedArray = sortedArray.filter(v => v);
This snippet also sorts the firstArrbased on the order of the defaultArray
此代码段还根据defaultArray的顺序对firstArr进行排序
like:
喜欢:
let firstArr = ['apple', 'kiwi', 'banana'];
let defaultArray = ['kiwi', 'apple', 'pear'];
...
console.log(sortedArray);
// ['kiwi', 'apple'];
回答by ChaseMedallion
If your values are non-null strings or numbers, you can use an object as a dictionary:
如果您的值是非空字符串或数字,则可以将对象用作字典:
var map = {}, result = [], i;
for (i = 0; i < array1.length; ++i) {
map[array1[i]] = 1;
}
for (i = 0; i < array2.length; ++i) {
if (map[array2[i]] === 1) {
result.push(array2[i]);
// avoid returning a value twice if it appears twice in array 2
map[array2[i]] = 0;
}
}
return result;