简体   繁体   中英

JavaScript comparing two arrays

Is there i way in JavaScript to compare two arrays;

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. In case only one element of array 1 match, element in array 2 return 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

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
only one element of array1 match, element in array2 return 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

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 :

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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