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);
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.
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 } }
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With