JavaScript find missing number in array

I have this array

var a = [5] , count  = 5;

I want to know the missing numbers on this array (a) and the result must be

1,2,3,4

I just try this but failed

var missing = [];

for ( var j = 0; j < a.length; j++ ) {
    for ( var i = 1; i <= count; i++ ) {
        if (a[j] != i) {
            missing.push( i );
        }
    }      
}

i called it at once its give

1,2,3,4

add some value to (a) array like

a = [2,3,4,5] 

its give me this

[1, 3, 4, 5, 1, 2, 4, 5, 1, 2, 3, 5, 1, 2, 3, 4]

how can i solve it find the missing numbers to the count value

note* find the missing numbers to the count value

Answer

You can do this with the use of indexOf function:

var a = [5],
  count = 5;
var missing = new Array();

for (var i = 1; i <= count; i++) {
  if (a.indexOf(i) == -1) {
    missing.push(i);
  }
}
console.log(missing); // to check the result.

Leave a Reply

Your email address will not be published. Required fields are marked *