Reputation: 105
Given a range, how is it possible in javascript to find the missing number in an unordered array? For example, if I know the range of an array is [48,79] and the array is:
[56, 76, 48, 69, 60, 68, 57, 58, 52,
72, 61, 64, 65, 66, 73, 75, 77,
49, 63, 50, 70, 51, 74, 54, 59,
78, 79, 71, 55, 67]
The missing number/output would be 62,53.
Upvotes: 0
Views: 461
Reputation: 527
EDIT: by the time I posted this, Vinay Kaklotar had posted a much better solution for the OPs updated question.
I would iterate until the missing value's index isn't found:
var arr = [1,2,3,4,5,7,8,9,10];
var i = 1;
while(arr.indexOf(i) !== -1) {
i++;
}
console.log(i);
The above was an answer to the original question before OP edited it. Below is a solution to the updated question.
I'm iterating through the array and comparing each item to a new sequence (n). Every time a missing number is found, it's added to the missing array.
var arr = [1, 2, 4, 5, 6, 9];
var missing = [];
var n = 1;
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== n) {
missing.push(n);
i--;
}
n++;
}
console.log(missing);
Upvotes: 1
Reputation: 424
You should try this
function findNumbers(arr) {
var sparse = arr.reduce((sparse, i) => (sparse[i]=1,sparse), []);
return [...sparse.keys()].filter(i => i && !sparse[i]);
}
var myArr = [56, 76, 48, 69, 60, 68, 57, 58, 52,
72, 61, 64, 65, 66, 73, 75, 77,
49, 63, 50, 70, 51, 74, 54, 59,
78, 79, 71, 55, 67]
var res= findNumbers(myArr );
console.log(res);
Upvotes: 2