简体   繁体   中英

how to compare two arrays of different length if you dont know the length of each one in javascript?

I am stuck in this. I got 2 arrays, I don't know the length of each one, they can be the same length or no, I don't know, but I need to create a new array with the numbers no common in just a (2, 10).

    var a = [2,4,10];
    var b = [1,4];

    var newArray = [];

    if(a.length >= b.length ){
        for(var i =0; i < a.length; i++){
            for(var j =0; j < b.length; j++){
                if(a[i] !=b [j]){
                    newArray.push(b);        
                }        
            }
        }
    }else{}  

It seems that you have a logic error in your code, if I am understanding your requirements correctly.

This code will put all elements that are in a that are not in b , into newArray .

var a = [2, 4, 10];
var b = [1, 4];

var newArray = [];

for (var i = 0; i < a.length; i++) {
    // we want to know if a[i] is found in b
    var match = false; // we haven't found it yet
    for (var j = 0; j < b.length; j++) {
        if (a[i] == b[j]) {
            // we have found a[i] in b, so we can stop searching
            match = true;
            break;
        }
        // if we never find a[i] in b, the for loop will simply end,
        // and match will remain false
    }
    // add a[i] to newArray only if we didn't find a match.
    if (!match) {
        newArray.push(a[i]);
    }
}

To clarify, if

a = [2, 4, 10];
b = [4, 3, 11, 12];

then newArray will be [2,10]

Try this

var a = [2,4,10]; 
var b = [1,4]; 
var nonCommonArray = []; 
for(var i=0;i<a.length;i++){
    if(!eleContainsInArray(b,a[i])){
        nonCommonArray.push(a[i]);
    }
}

function eleContainsInArray(arr,element){
    if(arr != null && arr.length >0){
        for(var i=0;i<arr.length;i++){
            if(arr[i] == element)
                return true;
        }
    }
    return false;
}

I found this solution just using the filter()<\/code> and include()<\/code> methods, a very and short easy one.

function compareArrays(a, b) {
  return a.filter(e => b.includes(e));
}

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