我如何才能找到两个数组中匹配的值? [英] How can I find matching values in two arrays?

查看:150
本文介绍了我如何才能找到两个数组中匹配的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,我希望能够比较两个,只返回匹配的值。例如两个数组有值的猫所以这就是将被退回。我还没有发现这样的事。什么是返回相似的最好方法?

  VAR数组1 = [猫,求和,好玩,运行];
VAR数组2 = [蝙蝠,猫,狗,太阳,小屋,肠];如果数组1值等于ARRAY2值,则返回匹配:猫


解决方案

当然,我的方法是通过第一阵列循环一次,并检查每个值的索引第二个数组中为止。如果该指数> -1 ,那么它放到返回的数组。

  Array.prototype.diff =功能(ARR2){
    VAR RET = [];
    对于(VAR我在这个){
        如果(arr2.indexOf(这由[i])-1个){
            ret.push(这由[i]);
        }
    }
    返回RET;
};


我的解决方案不使用两个循环像其他人,因此它可能跑快一点。如果你想避免使用的for..in ,你既可以先数组排序,以重新编制的所有值:

  Array.prototype.diff =功能(ARR2){
    VAR RET = [];
    this.sort();
    arr2.sort();
    对于(VAR I = 0; I< this.length; I + = 1){
        如果(arr2.indexOf(这由[i])-1个){
            ret.push(这由[i]);
        }
    }
    返回RET;
};

使用看起来像:

  VAR数组1 = [猫,求和,好玩,运行,小屋];
VAR数组2 = [蝙蝠,猫,狗,太阳,小屋,肠];的console.log(array1.diff(数组2));

如果你有一个问题/问题扩展阵列的原型,你可以很容易地将其更改到一个函数。

  VAR差异=功能(ARR,ARR2){

和原来的地方说FUNC你随时随地更改这个 ARR2

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 array1 value is equal to array2 value then return match: cat

解决方案

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;
};

​ 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;
};

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.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

这篇关于我如何才能找到两个数组中匹配的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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