Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 752
Максим Зубков Avatar asked May 17 '16 13:05

Максим Зубков


Video Answer


2 Answers

Better way to deal with dynamic MIN & MAX numbers to find range of missing number in an array

const findMissing = num => {
  const max = Math.max(...num); // Will find highest number
  const min = Math.min(...num); // Will find lowest number
  const missing = []

  for(let i=min; i<= max; i++) {
    if(!num.includes(i)) { // Checking whether i(current value) present in num(argument)
      missing.push(i); // Adding numbers which are not in num(argument) array
    }
  }
  return missing;
}

findMissing([1,15]);
like image 133
shahab kadri Avatar answered Sep 22 '22 10:09

shahab kadri


The missing number can be found by finding total (n*(n+1)/2) and subtract total from each value the renaming number will be the required number.

function findNumber(arr) {
  var n = arr.length;
  var total = ((n + 2) * (n + 1)) / 2;
  for (let i = 0; i < n; i++) {
    total -= arr[i];
  }
  return total;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(findNumber(arr));
like image 22
Adnan Avatar answered Sep 19 '22 10:09

Adnan