How to compare two arrays of different lengths if you do not know the length of each of them in javascript?

I am stuck in this. I have 2 arrays, I do not know the length of each of them, they can be the same length or not, I do not know, but I need to create a new array with numbers that are not found just in (2, 10).

In this case:

    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{}  

I don’t know why my code never reaches the first condition, and I don’t know what to do if b is longer than.

+5
source share
2 answers

It seems that you have a logical error in your code if I understand your requirements correctly.

This code will put all elements that are in a, which are not in b, in 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]);
    }
}

,

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

newArray [2,10]

+7


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;
}
+2

All Articles