'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).

For 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 reach the first condition and I don't know what to do when b has more length than a.



Solution 1:[1]

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

Solution 2:[2]

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

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Selvakumar Ponnusamy
Solution 2 SadVitorGomez