比较两个数组并将不同的值推送到新数组 [英] Compare two arrays and push different values to new array

查看:95
本文介绍了比较两个数组并将不同的值推送到新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要比较的数组,并将两个都不相同的值推送到新数组中。基本上,我试图将arrayOne中没有的arrayTwo值推到新数组中。

I have two arrays that I want to compare and push values that are not the same in both to a new array. Basically I'm trying to push values from arrayTwo that are not in arrayOne to a new array.

  var arrayOne = [[1,"121"], [2,"111"], [2,"321"], [3,"232"], [3,"213"], [4,"211"]],
  arrayTwo = [[4,"111"], [1,"131"], [3,"321"], [3,"232"], [3,"211"], [3,"213"], [1, "X1X"]];
  doNotMatch = []; 

我尝试遍历前两个数组,比较如下所示的值,但这显然行不通:

I tried looping through the first two arrays comparing the values like below but this obviously isn't working:

 for ( var i = 0; i < arrayOne.length; i++ ) {
        for ( var e = 0; e < arrayTwo.length; e++ ) {
            if ( arrayOne[i] !== arrayTwo[e]) {
                doNotMatch.push(arrayTwo[e])
                } 
        }
    }


推荐答案

var arrayOne = ["dog", "cat", "hamster", "gerbil", "turtle"],
    arrayTwo = ["hamster", "turtle", "gerbil"],
    doNotMatch = []; 

for(var i=0;i<arrayOne.length;i++){
   if(arrayTwo.indexOf(arrayOne[i])==-1){doNotMatch.push(arrayOne[i]);}
}

//doNotMatch is now ["dog","cat"]

这篇关于比较两个数组并将不同的值推送到新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆