如何在两个数组中找到匹配的值? [英] How can I find matching values in two arrays?
问题描述
我有两个数组,我希望能够比较两者并只返回匹配的值.例如,两个数组的值都是 cat
,因此将返回该值.我没有找到这样的东西.返回相似性的最佳方法是什么?
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?
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
推荐答案
当然,我的方法是遍历第一个数组一次并检查第二个数组中每个值的索引.如果索引是 >-1
,然后push
到返回的数组上.
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.
Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};
我的解决方案不像其他人那样使用两个循环,因此它可能运行得更快一些.如果您想避免使用 for..in
,您可以先对两个数组进行排序以重新索引它们的所有值:
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:
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;
};
用法如下:
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log(array1.diff(array2));
如果您在扩展 Array 原型时遇到问题,可以轻松地将其更改为函数.
If you have an issue/problem with extending the Array prototype, you could easily change this to a function.
var diff = function(arr, arr2) {
并且您可以将 func 最初表示 this
的任何地方更改为 arr2
.
And you'd change anywhere where the func originally said this
to arr2
.
这篇关于如何在两个数组中找到匹配的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!