简体   繁体   English

JavaScript比较两个数组

[英]JavaScript comparing two arrays

Is there i way in JavaScript to compare two arrays; 我有办法在JavaScript中比较两个数组吗?

This is my example. 这是我的例子。

array1 = ['jpg','png'];

array 2 = ['jpg','pdf','png','bmp'];

I my case i need if are all elements of array1 part of array2 return TRUE, or something. 我的情况下,我是否需要array2的所有元素都返回TRUE,或其他。 In case only one element of array 1 match, element in array 2 return FALSE. 如果只有数组1中的一个元素匹配,数组2中的元素将返回FALSE。 Order its not important. 命令其不重要。 Basciclly this is validation of uploaded files, i try to removing button, if two file are not with right extension. 基本上,这是对上传文件的验证,如果两个文件的扩展名不正确,我会尝试删除按钮。

I try function inarray, but i think it only works with string not array 我尝试函数inarray,但我认为它仅适用于字符串而不适用于array

If legacy is not a problem, Something like this would do: 如果遗留问题不成问题,则可以执行以下操作:

var array1 = ['jpg','png','d'];
var array2 = ['jpg','pdf','png','bmp'];

var result = !array1.filter(function(a) { return array2.indexOf(a)==-1; }).length;   

// result is False

if are all elements of array1 part of array2 return TRUE 如果array1 所有元素都是array2一部分,则返回TRUE
only one element of array1 match, element in array2 return FALSE 只有array1一个元素匹配, array2元素返回FALSE

You can think about this in two ways, 您可以通过两种方式考虑这一点,

  • take the intersection and check the intersection is the same as the input 取交点并检查交点是否与输入相同
  • loop over the input and return false on the first mismatch 循环输入,并在第一个不匹配时返回false

Here is an example of using a loop 这是使用循环的示例

var a = [1, 3],
    b = [1, 5],
    c = [0, 1, 2, 3, 4];

function test(needles, haystack) {
    var i;
    for (i = 0; i < needles.length; ++i) {
        if (haystack.indexOf(needles[i]) === -1) {
            return false;
        }
    }
    return true;
}

test(a, c); // true
test(b, c); // false

If the result of filtering the second array with the values of the first is an array with length equal to the length of the first array, the first array is a subset of the second. 如果使用第一个数组的值过滤第二个数组的结果是长度等于第一个数组的长度的数组,则第一个数组是第二个数组的子集。 You can write a function for that, or assing an extra method to Array.prototype : 您可以为此编写一个函数,或者为Array.prototype附加一个方法:

 var array1 = ['jpg', 'png']; var array2 = ['jpg', 'pdf', 'png', 'bmp']; var array3 = ['jpg', 'bmp', 'pdf']; Helpers.log2Screen('array1 subset of array2? ', isSubset(array1, array2) ? 'yes' : 'no' ); // assign and use Array.prototype.subsetOf Array.prototype.subsetOf = isSubsetProto; Helpers.log2Screen('array1 subset of array3? ', array1.subsetOf(array3) ? 'yes' : 'no' ); function isSubset(arr1, arr2) { return arr2.filter( function (v) {return arr1.indexOf(v) > -1; } ).length == arr1.length; } function isSubsetProto(arr) { return arr.filter( function (v) {return this.indexOf(v) > -1; }, this ).length == this.length; } 
 <script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM