JavaScript数组长度比较

时间:2018-07-11 12:41:49

标签: javascript arrays loops

在我的代码中,我检查两个数组中是否存在相似的值,以及是否存在相似的值,但不会在结果中显示它们,但是,如果我执行相同的检查但切换了数组的长度,这意味着Array2比Array1长,结果为空,数组为空。即使在切换数组的长度后,如何获得相同的结果?

我的代码:

    var Array2 = [ "1", "2", "3", "4", "5" ]; 
    var Array1 = ["1","2","3"];
      
    var result = [];
      
    
    for(var i = 0; i < Array1.length ; i++){
        
        var x = Array1[i];
        var check = false;        
      
        for( var y = 0; y < Array2.length; y++){
          
          if(x == Array2[y]){
           
            check = true;
          }
        }
        if(!check){
          result.push(x);
        }
    }
    console.log(result);

3 个答案:

答案 0 :(得分:3)

您可以使用ES6 .filter()方法从数组中删除重复项。

ES6方法:


let Array2 = [ "1", "2", "3", "4", "5" ]; 
let Array1 = ["1","2","3"];

let result = Array2.filter(val => !Array1.includes(val));

console.log(result);

香草JS方法:


let Array1 = ["1", "2", "3"];
let Array2 = ["1", "2", "3", "4", "5"];

function getMissing(a, b) {
  var missings = [];
  var matches = false;

  for (let i = 0; i < a.length; i++) {
    matches = false;
    for (let e = 0; e < b.length; e++) {
      if (a[i] === b[e]) matches = true;
    }
    if (!matches) missings.push(a[i]);
  }
  return missings;
}

console.log(getMissing(Array2, Array1));

jQuery方法:


let Array1 = ["1", "2", "3"];
let Array2 = ["1", "2", "3", "4", "5"];

let difference = $(Array2).not(Array1).get();

console.log(difference);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:2)

尝试关注

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];

var result = [...Array1.filter(v => !Array2.includes(v)), ...Array2.filter(v => !Array1.includes(v))];
console.log(result);

可以使用以下方法提高性能

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];

var map2 = Array2.reduce((a,c) => Object.assign(a, {[c]:true}), {});
var map1 = Array1.reduce((a,c) => Object.assign(a, {[c]:true}), {});

var result = [...Object.keys(map2).filter(k => !map1[k]), ...Object.keys(map1).filter(k => !map2[k])];
console.log(result);

答案 2 :(得分:0)

粗俗的方式

var Array2 = [ "1", "2", "3", "4", "5" ]; 
var Array1 = ["1","2","3"];
var result = [];
var matches = false;

if(Array2.length >= Array1.length){
  getUnique(Array2,Array1);
}
else{
  getUnique(Array1,Array2);
}


function getUnique(maxArray,minArray){
  $.each(maxArray,function(n1,i1){
     matches = false;
     $.each(minArray,function(n2,i2){
           if(i1 === i2){
             matches = true;
            }          
      });
      if(!matches){
        result.push(i1);
      }
  });
}
console.log(result);