Created
March 3, 2017 09:36
-
-
Save nageshwar-old/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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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