Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
bentham Avatar asked Nov 18 '11 05:11

bentham


3 Answers

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]

like image 198
BudgieInWA Avatar answered Nov 03 '22 18:11

BudgieInWA


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;
}
like image 20
Selvakumar Ponnusamy Avatar answered Nov 03 '22 16:11

Selvakumar Ponnusamy


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));
}
like image 26
SadVitorGomez Avatar answered Nov 03 '22 16:11

SadVitorGomez