18

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

4
  • You should just get lodash to do this for you Commented May 17, 2016 at 13:45
  • what do you mean by find the missing numbers to the count value Commented May 17, 2016 at 13:47
  • @Manish the count value its 5 so i want the missing value to the 5 if its 20 i want missing value to number 20 Commented May 17, 2016 at 13:48
  • that means you need first 5 missing values if count is 5 or is it like whatever missing values less then 5 Commented May 17, 2016 at 13:51

25 Answers 25

31

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.

Sign up to request clarification or add additional context in comments.

Comments

14

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]);

1 Comment

Best solution I've seen so far
9

Use indexOf() to check element in array or not

var a = [5],
  count = 5,
  missing = [];

for (var i = 1; i <= count; i++) {
  if (a.indexOf(i) == -1) {
    missing.push(i);
  }
}

document.write('<pre>' + JSON.stringify(missing) + '</pre>');

Comments

6

A one-line ES6 riff:

let missingNumbers = (a, l=true) => Array.from(Array(Math.max(...a)).keys()).map((n, i) => a.indexOf(i) < 0  && (!l || i > Math.min(...a)) ? i : null).filter(f=>f);

By default returns numbers missing from a sequence of more than one number:

array = [2, 5, 9]
missingNumbers(array)
// returns [3, 4, 6, 7, 8]

But you can set the low-value flag to false and get a result starting with 1:

missingNumbers(array, false)
// returns [1, 3, 4, 6, 7, 8]

missingNumbers([5])
// returns [1, 2, 3, 4]

or simply define the function without the flag

let missingNumbers = (a) => Array.from(Array(Math.max(...a)).keys()).map((n, i) => a.indexOf(i) < 0? i : null).filter(f=>f);

Comments

5

Try running the code snippet

var a = [1,4,7], count = a[a.length - 1];
var missing = [];
for ( var i = 1; i <= count; i++ ) {
	if (a.indexOf(i) == -1) {
		missing.push(i);
	}
}
alert(missing.toString());

Comments

4

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));

3 Comments

This only works for sorted arrays without duplicates does it not?
@BrianSterling works for any order
This gives almost comically bad results for most input. For example, the array from the question ([5]) gives -2, instead of the requested [1,2,3,4]. Similarly, when there is more than one element missing or the array does not start at 1.
2

function missingItems(arr, n) {
  let missingItems = [];
  for (let i = 1; i <= n; i++) if (!arr.includes(i)) missingItems.push(i);
  return missingItems;
}
console.log(missingItems([9, 1, 4, 2, 10, 6], 10));

Although this solution would take a time complexity of 0(n), you could easily get all the missing items between 1 and n by running a loop from 1 to n and checking if the index exists in the array arr on each iteration.

1 Comment

Complexity is O(n*m) (or O(n²) assuming array length and number of elements in range is more or less equal), for each element in the range you have to go through the array.
1

Simple

consider _ is lodash or underscore

var arr = [2,3,4,5];

var min = _.min(arr);
var result = [];

for (var i = 0; i < min; i++) {
    result.push(i);
}

result // [0, 1];

Comments

1

You could switch your loops around and set a flag. This may not be the fastest method, but it worth looking at since this is the first thoughts you had.

The Fix

Example: jsFiddle

var missing = [];
var a = [5];
var count = 5;
var found = false;

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

alert(JSON.stringify(missing));

Comments

0

One way is to find missing numbers by using this:

Array.from({length: Math.max(...b)},(_,x) => !b.includes(x+1)?x+1:false).filter(Boolean)

Comments

0

var a = [100,1,4,7];
a.sort(function(a, b) {
      return a - b;
      });
count = a[a.length - 1];
var missing = [];
for ( var i = 1; i <= count; i++ ) {
	if (a.indexOf(i) == -1) {
		missing.push(i);
	}
}
console.log(missing.toString());

2 Comments

When answering an old question, your answer would be much more useful to other StackOverflow users if you included some context to explain how your answer helps, particularly for a question that already has an accepted answer. See: How do I write a good answer.
Thanks for your feed back. I will following the above link.
0

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.

Comments

0

Lodash solution:
It will work for any number that are missing between the min & max of array values.

let numbersArray = [0, 1, 3, 6, 7];
let missedNumbersArray = [];
_.forEach(_.range(_.min(numbersArray), _.max(numbersArray)), (number, index) => {
    if (_.findIndex(numbersArray, val => val == number) == -1) {
        missedNumbersArray.push(index);
    }
});

2 Comments

Why? why would you choose this instead of vanilla JS?
Best of vanilla js & jquery answers are already given. I feel many people are still looking for lodash based solutions (Myself searched for the one) for their react or similar framework based projects.
0
const myFunc = (arr) => {
  const sum = ((arr.length + 1) * (arr.length + 2)) / 2;
  const arrSum = (arr) => arr.reduce((a, b) => a + b, 0);
  return sum - arrSum(arr);
};
const myArray = [1, 2, 10, 5, 6, 4, 7, 9, 3, 11];
console.log(myFunc(myArray));

Explanation:

  1. Storing sum of natural numbers in  "sum" variable up to one more of length of array. We are adding one more to the length of the array because one number is missing. To calculate the sum, we are using the sum of n natural number formula i.e  n*(n+1)/2.
  2. Now calculating the sum of our given array using reduce().
  3. It is clear that one number is missing from our Array so subtracting the sum of the given array from the sum of natural numbers will give us the missing number.

1 Comment

the result should be array of the numbers that are missing, but your result is just a number
0

You can do this with the use of XOR operator:

let arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
let x1 = xorOfArray(arr1, arr1.length); // 8
console.log(x1);

let arr2 = [1, 2, 3, 4, 5, 7, 8]; // 6 is missing
let x2 = xorOfArray(arr2, arr2.length); // 14
console.log(x2);

let arr3 = [x1, x2];
let x3 = xorOfArray(arr3, arr3.length); // 6
console.log(x3);
// x3 is the missing number

function xorOfArray(arr, n) 
{ 
    // Resultant variable 
    let xor_arr = 0; 
  
    // Iterating through every element in 
    // the array 
    for (let i = 0; i < n; i++) { 
  
        // Find XOR with the result 
        xor_arr = xor_arr ^ arr[i]; 
    } 
  
    // Return the XOR 
    return xor_arr; 
} 

1 Comment

Lol, I like how you write in your code "6 is missing" and below it as answer "14", as if this is the obvious and satisfying result.
0
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)
    
    const filterArr= [...new Set(A.filter(x=> x>0).sort())];
   
    let k=1;
    
    function newArr(){
        for(let i=0;i<filterArr.length;i++){
            if(filterArr[i]=== k){
                    k++;
            }
            else{
                return k;
            }
        }
        return k;
      }
    
    return filterArr.length? newArr():1;  
}
console.log(solution([3,2,1,5]));   output:4

console.log(solution([-1,-2.-5]));  output: 1

console.log(solution([1,2.3,4]));   output: 5

Comments

0

That's only for sequenced array:

const findMissingNumber = (arr) => {
  for (let i = 1; i <= arr.length; i++) {
    if (arr[i - 1] !== i) {
      return i;
    }
  }
}
const arr = [1, 2, 3, 4, 5, 6, 8, 10];
console.log(findMissingNumber(arr));

Comments

0

Finding the missing numbers of given array using javascript;

//add a sorting function to get exact output

let len = parseInt(prompt("Enter the range : "));
let arr = [];let i = 0;
for (i = 0; i < len;i++){
    let num = parseInt(prompt("Enter the numbers : "));
    arr.push(num);
    /*arr.sort(function(a,b){
          return a - b;
    });*/
}

missingNum = (arr) => {
    let i = 0,j = 0;
    let start = arr[0];
    let end = arr[arr.length - 1];
    let miss = [];
    let found = false;
    let result = "";

for (i = start; i<=end; i++){
    found = false;
    for(j = 0;j<arr.length;j++){
        if(arr[j] == i){
            found = true ;
            break;
        }   
    }
    if(!found){
        miss.push(i)
    }
}
return  miss;
}
console.log(missingNum(arr))

1 Comment

Your answer could be improved by providing an explanation of how your code works.
0
function missingArray(params) {
    var arr =[1,3,5,8,9];
    var missing = []; 
    for (let i = 0; i < arr[arr.length-1]; i++) {
        if(!(arr.includes(i))){
           missing.push(i);
        }
       
    }
    return missing;
}

console.log(missingArray());

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

arr=[1,2,3,9]

 newArr=[]
 for(let i=1;i<Math.max(...arr);i++){
   if(arr.indexOf(i)===-1){
     newArr.push(i)
   }
 }

 console.log(newArr)

Comments

0
function findMissingNumbers(arr) {
  // sort the array in ascending order
  arr.sort(function(a, b) {
    return a - b;
  });

  // initialize the missing numbers array
  const missing = [];

  // iterate through the array
  for (let i = 0; i < arr.length - 1; i++) {
    // calculate the difference between the current and next number
    const diff = arr[i + 1] - arr[i];

    // if the difference is greater than 1, there is a missing number(s)
    if (diff > 1) {
      // push the missing number(s) into the array
      for (let j = 1; j < diff; j++) {
        missing.push(arr[i] + j);
      }
    }
  }

  // return the missing numbers array
  return missing;
}

Comments

0

Brute, buffer and best solutions just with pure JS:

const nums = [1,2,3,4,6];

// Brute sol
// Time complexity = O(n2)
// Space complexity = O(n)

const findMissingNumberBrute = (nums, n) => {
    for(let i = 1; i <= n - 1; i++) {
        let flag = 0;
        for(let j = 0; j <= n; j++) {
            if(nums[j] == i) {
                flag = 1;
            }
        }
        if(flag === 0) {
            return i;
        }
    }
    
}

// 5
console.log(findMissingNumberBrute(nums, 6))

// Buffer sol
// Time complexity = O(n) + O(n)
// Space complexity = O(n)

const findMissingNumberBuffer = (nums, n) => {
    const obj = {};
    for(let i = 0; i < n-1; i++) {
        obj[nums[i]] = 1
    }
    for(let j = 1; j <= n; j++) {
        if(obj[j] === undefined) {
            return j
        }
    }
}

// 5
console.log(findMissingNumberBuffer(nums, 6))


// Best sol
// Time complexity = O(n)
// Space complexity = O(1)

const findMissingNumberBest = (nums, n) => {
    // get the sum of first n natural numbers
    const totalSumOfFirstNNumners = (n*(n+1)/2);
    let sum = 0;

    for(let i = 0; i <= nums.length -1; i++) {
        sum = sum + nums[i]
    }
    return totalSumOfFirstNNumners - sum;
}

// 5
console.log(findMissingNumberBest(nums, 6))

// Best1 with xor sol
// Time complexity = O(1)
// Space complexity = O(1)

const findMissingNumberBest1 = (nums, n) => {
    // get the sum of first n natural numbers
    let xor1 = 0;
    for(let i = 0; i <= n; i++) {
        xor1 = xor1 ^ i;
    }
    let xor2 = 0;
    for(let j = 0; j <= n - 1; j++) {
        xor2 = xor2 ^ nums[j];
    }

    return xor1 ^ xor2;
}

// 5
console.log(findMissingNumberBest1(nums, 6))

Comments

0
class Solution{
    missingNumber(array,n){ 
     let res = 0;
        for (let i = 0; i <= n; i++)  res ^= i;  
        
        for (let i = 0; i < n-1; i++) res ^= array[i]
       return res
    }
}

N = 10
A = [6,1,2,8,3,4,7,10,5]

const find = new Solution()
console.log(find.missingNumber(A, N))

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

Missing element in array code for sequence or non sequence array

const arry = [2,6,5,11,9,13];

function missing(arr) {

let s = arr[0];

let missingArr = [];

  for (let i = 0; i < arr[arr.length-1]; i++) {   
    
    if(s !== arr[arr.length-1]) {
    
      if(!arr.includes(s)) {
            missingArr.push(s)
       };

       s = s+1;
    };
  
  }
  
  return missingArr;
};

console.log('====>>>', missing(arry));

Comments

-1

This is how to find missing number in a array(sorted array),
It checks only one missing number.

function miss(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== i + 1) {
      return i + 1;
    }
  }
}
let a = miss([1, 2, 3, 4, 5, 7, 8, 9, 10])
console.log(a)

function missing(arr) {
  let n = arr.length;
  let sum = (n + 1) * (n + 2) / 2
  let total = arr.reduce((acc, item) => acc + item);
  let missin = sum - total
  return missin

}

let b = missing([1, 2, 3, 4, 6, 7, 8, 9]);
console.log(b)

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.