comparing two javascript arrays?

前端 未结 3 1152
情歌与酒
情歌与酒 2021-01-29 10:47

I want to compare two arrays with each other and see if there is a match, and if there is do something.

var answers = new Array(\"a\",\"b\",\"c\",\"d\", \"e\");
         


        
3条回答
  •  野性不改
    2021-01-29 11:28

    Try this code:

    var a = [1,2,3,4]
      , b = [1,3,5,7,9]
      , c = ['a','b','c'];
    
    function findDups( arr1, arr2 ) {
      var arrs = [ arr1, arr2 ].sort(function( a,b ) {
        return a.length > b.length;
      });
      return arrs[0].filter(function( v ) {
        return ~arrs[1].indexOf( v ); 
      });
    }
    
    function hasDups( arr1, arr2 ) {
      return !!findDups( arr1, arr2 ).length;
    }
    
    console.log( findDups( a,b ) ); //=> [1, 3]
    console.log( hasDups( a,c ) ); //=> false
    

提交回复
热议问题