MG2016
MG2016

Reputation: 319

Javascript Array comparing Issue

How can I run the else part only after the end of the loop here? So right now: 10 is compared with 10, 20, 30. Then 40 is compared with 10, 20, 30. I want to get 40 only after it's been compared with all the values (10, 20, 30). I will want to do some calculations when 40 is missing from array 2. Right now it would be 40 == 10, it;s missing, do calculations, but I need it to compare all values then do the calculation.

alert("start")
var array1 = [10, 40];
var array2 = [10, 20, 30];
for (var x = 0; x < array2.length; x++) {
  for (var y = 0; y < array1.length; y++) {
    if (array1[y] != array2[x]) {
      alert("Not Found")
    } else {
      alert("Found")
    }
  }
}

Upvotes: 0

Views: 84

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386654

Some suggestions:

  • change the iteration; start with array1 as outer loop and use array2 as inner loop, because you need a summary of an item is inside of array2.

  • use an indicator if the item is found.

  • evaluate the indicator and take the action you need.

document.write("start<br>");
var array1 = [10, 40],
    array2 = [10, 20, 30],
    x, y, found;

for (x = 0; x < array1.length; x++) {
    found = false;
    for (y = 0; y < array2.length; y++) {
        if (array1[x] === array2[y]) {
            found = true;
        }
    }
    if (!found) {
        document.write(array1[x] + ' not found!<br>');
    }
}
document.write("end");

Basically the same as above, but shorter

var array1 = [10, 40],
    array2 = [10, 20, 30];

array1.forEach(function (a) {
    if (!~array2.indexOf(a)) {
        document.write(a + ' not found!');
    }
});

Upvotes: 1

Nelson Melecio
Nelson Melecio

Reputation: 1494

Try this:

alert("start")

var array1 = [10, 40];
var array2 = [10, 20, 30];


for (var x = 0; x < array1.length; x++) {

  var count = 0;

  for (var y = 0; y < array2.length; y++) {
   	     if(array1[x] == array2[y]) {
         count++;
     }
  }

  if (count > 0) {
       alert("Found")
  } else {
       alert("Not Found")
       // do your calculation here
  }

}

Upvotes: 2

Flash Thunder
Flash Thunder

Reputation: 12036

alert("start")
var array1 = [10, 40];
var array2 = [10, 20, 30];
for (var x = 0; x < array1.length; x++) {
   if(array2.indexOf(array1[x]) == -1) console.log(array1[x] + ' from array 1 not found in array 2');
}

for (var x = 0; x < array2.length; x++) {
   if(array1.indexOf(array2[x]) == -1) console.log(array2[x] + ' from array 2 not found in array 1');
}

FIDDLE

Upvotes: 1

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

You can use Array.prototype.filter()

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

var array1 = [10, 40];
var array2 = [10, 20, 30];

array1.diff(array2); //[40]

Upvotes: 3

Related Questions