Arrays - Find missing numbers in a Sequence

2020-05-18 16:25发布

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

14条回答
老娘就宠你
2楼-- · 2020-05-18 17:24
const findMissing = (numarr) => {
  for(let i = 1; i <= numarr.length; i++) {
      if(i - numarr[i-1] !== 0) {
        console.log('found it', i)
        break;
      } else if(i === numarr.length) console.log('found it', numarr.length + 1)
    }
  };

console.log(findMissing([1,2,3,4,5,6,7,8,9,10,11,12,13,14]))
查看更多
Root(大扎)
3楼-- · 2020-05-18 17:24

It would be fairly straightforward to sort the array:

numArray.sort();

Then, depending upon what was easiest for you:

  1. You could just traverse the array, catching sequential patterns and checking them as you go.
  2. You could split the array into multiple arrays of sequential numbers and then check each of those separate arrays.
  3. You could reduce the sorted array to an array of pairs where each pair is a start and end sequence and then compare those sequence start/ends to your other data.
查看更多
登录 后发表回答