0

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")
    }
  }
}

4 Answers 4

3

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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
  }

}

Comments

1
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

Comments

1

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!');
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.