0

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.

2
  • 3
    You might iterate over the array and cross off the elements in the range as you come across them. What have you tried? Commented Mar 3, 2020 at 3:03
  • what you did so far ? Commented Mar 3, 2020 at 3:23

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

unfortunately, the array I am working with has a range of [48,72], with multiple numbers potentially missing. I just gave the 1-10 as an example. I do like the logic here but do not see how it would expand to my situation
It would be helpful in the future for you to include that information in your question. The answer is a correct answer for the question you gave. I'll update my answer, but please be more specific.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.