Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nageshwar521/9715abd541d5cb11293d2e50e662cdfe to your computer and use it in GitHub Desktop.
Save nageshwar521/9715abd541d5cb11293d2e50e662cdfe to your computer and use it in GitHub Desktop.
finding the missing numbers in an array, it will format the missed numbers in range format and also it will ignore if the element is not a number
function missingNumbers(nums) {
var missedNums = [];
var sortedArr = nums.sort(function(a, b) {
return a - b;
});
sortedArr.forEach(function(ele, i, arr) {
var a = +arr[i],
b = +arr[i + 1];
if (!b) return;
if (isNaN(b)) {
arr.splice(i + 1, 1);
return;
}
var numGap = b - a;
if (numGap == 2) missedNums.push(a + numGap - 1);
if (numGap > 2) {
var formatNum = (a + 1) + "-" + (a + numGap - 1);
missedNums.push(formatNum);
}
})
return missedNums;
}
console.log(missingNumbers([3, "num", "4", undefined, null, {a:2}, false, 7, 1, "76", 34, "23", 32, 99, 56]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment