Javascript 比较两个返回差异的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10927722/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:36:47  来源:igfitidea点击:

Compare 2 arrays which returns difference

javascriptjqueryarraysarray-difference

提问by Howdy_McGee

What's the fastest/best way to compare two arrays and return the difference? Much like array_diffin PHP. Is there an easy function or am I going to have to create one via each()? or a foreachloop?

比较两个数组并返回差异的最快/最佳方法是什么?很像array_diff在 PHP 中。是否有一个简单的功能,或者我将不得不通过创建一个each()?还是foreach循环?

回答by superphonic

I know this is an old question, but I thought I would share this little trick.

我知道这是一个老问题,但我想我会分享这个小技巧。

var diff = $(old_array).not(new_array).get();

diffnow contains what was in old_arraythat is not in new_array

diff现在包含old_array不在的内容new_array

回答by Tats_innit

Working demohttp://jsfiddle.net/u9xES/

工作演示http://jsfiddle.net/u9xES/

Good link (Jquery Documentation): http://docs.jquery.com/Main_Page{you can search or read APIs here}

好的链接(Jquery 文档):http: //docs.jquery.com/Main_Page{你可以在这里搜索或阅读 API}

Hope this will help you if you are looking to do it in JQuery.

如果您希望在 JQuery 中做到这一点,希望这对您有所帮助。

The alert in the end prompts the array of uncommon element Array i.e. difference between 2 array.

警报到底提示了不常见元素的数组 Array 即 2 数组之间的差异。

Please lemme know if I missed anything, cheers!

如果我错过了什么,请让我知道,干杯!

Code

代码

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var difference = [];

jQuery.grep(array2, function(el) {
        if (jQuery.inArray(el, array1) == -1) difference.push(el);
});

alert(" the difference is " + difference);? // Changed variable name 

回答by anurag_29

use underscore as :

使用下划线作为:

_.difference(array1,array2)

回答by Kareem

/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

然后,您可以在代码中的任何位置调用该函数。

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

这适用于所有情况并避免上述方法中的问题。希望有帮助!

回答by Kareem

var arrayDiff = function (firstArr, secondArr) {
    var i, o = [], fLen = firstArr.length, sLen = secondArr.length, len;


    if (fLen > sLen) {
        len = sLen;
    } else if (fLen < sLen) {
        len = fLen;
    } else {
        len = sLen;
    }
    for (i=0; i < len; i++) {
        if (firstArr[i] !== secondArr[i]) {
            o.push({idx: i, elem1: firstArr[i], elem2: secondArr[i]});  //idx: array index
        }
    }

    if (fLen > sLen) {  // first > second
        for (i=sLen; i< fLen; i++) {
            o.push({idx: i, 0: firstArr[i], 1: undefined});
        }
    } else if (fLen < sLen) {
        for (i=fLen; i< sLen; i++) {
            o.push({idx: i, 0: undefined, 1: secondArr[i]});
        }
    }    

    return o;
};

回答by Dries

if you also want to compare the order of the answer you can extend the answer to something like this:

如果您还想比较答案的顺序,您可以将答案扩展为以下内容:

Array.prototype.compareTo = function (array2){
    var array1 = this;
    var difference = [];
    $.grep(array2, function(el) {
        if ($.inArray(el, array1) == -1) difference.push(el);
    });
    if( difference.length === 0 ){
        var $i = 0;
        while($i < array1.length){
            if(array1[$i] !== array2[$i]){
                return false;
            }
            $i++;
        }
        return true;
    }
    return false;
}

回答by Behnam Rasooli

In this way you don't need to worry about if the first array is smaller than the second one.

这样您就不必担心第一个数组是否小于第二个数组。

var arr1 = [1, 2, 3, 4, 5, 6,10],
    arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function array_diff(array1, array2){
    var difference = $.grep(array1, function(el) { return $.inArray(el,array2) < 0});
    return difference.concat($.grep(array2, function(el) { return $.inArray(el,array1) < 0}));;
}

console.log(array_diff(arr1, arr2));

回答by Jonas H?gh

Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.

像这样的数组操作并不是 jQuery 的强项。您应该考虑使用 Underscorejs 之类的库,特别是差异函数。

回答by Elvis

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

这应该适用于未排序的数组、双精度值和不同的顺序和长度,同时为您提供来自 array1、array2 或两者的过滤值。

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

回答by Maksym Kalin

The short version can be like this:

简短版本可以是这样的:

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

result:

结果:

diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]