Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays - Find missing numbers in a Sequence

I'm trying to find an easy way to loop (iterate) over an array to find all the missing numbers in a sequence, the array will look a bit like the one below.

var numArray = [0189459, 0189460, 0189461, 0189463, 0189465];

For the array above I would need 0189462 and 0189464 logged out.

UPDATE : this is the exact solution I used from Soufiane's answer.

var numArray = [0189459, 0189460, 0189461, 0189463, 0189465]; var mia= [];      for(var i = 1; i < numArray.length; i++)      {              if(numArray[i] - numArray[i-1] != 1)          {                      var x = numArray[i] - numArray[i-1];             var j = 1;             while (j<x)             {                 mia.push(numArray[i-1]+j);                 j++;             }         }     } alert(mia) // returns [0189462, 0189464] 

UPDATE

Here's a neater version using .reduce

var numArray = [0189459, 0189460, 0189461, 0189463, 0189466];  var mia = numArray.reduce(function(acc, cur, ind, arr) {    var diff = cur - arr[ind-1];    if (diff > 1) {      var i = 1;      while (i < diff) {        acc.push(arr[ind-1]+i);        i++;      }    }    return acc;  }, []);  console.log(mia);
like image 760
Mark Walters Avatar asked Sep 06 '11 09:09

Mark Walters


People also ask

How do you find multiple missing elements in an array?

To find the multiple missing elements run a loop inside it and see if the diff is less than arr[i] – i then print the missing element i.e., i + diff. Now increment the diff as the difference is increased now. Repeat from step 2 until all the missing numbers are not found.


2 Answers

If you know that the numbers are sorted and increasing:

for(var i = 1; i < numArray.length; i++) {     if(numArray[i] - numArray[i-1] != 1) {            //Not consecutive sequence, here you can break or do whatever you want     } } 
like image 122
Soufiane Hassou Avatar answered Sep 18 '22 01:09

Soufiane Hassou


ES6-Style

var arr = [0189459, 0189460, 0189461, 0189463, 0189465];  var [min,max] = [Math.min(...arr), Math.max(...arr)]; var out = Array.from(Array(max-min),(v,i)=>i+min).filter(i=>!arr.includes(i)); 

Result: [189462, 189464]

like image 26
SammieFox Avatar answered Sep 17 '22 01:09

SammieFox