0

So I have a function that finds the missing number given upper and lower bounds and the function logic works fine as

const findMissingNumber = (arr, upperBound, lowerBound) => {
    arr = arr.sort((a, b) => a - b);
    let correctArray = [lowerBound];
    for (let i = 1; i < upperBound; i++, lowerBound++) {
        if (lowerBound + 1 < upperBound)
            correctArray[i] = lowerBound + 1;
        else
            break
    }
    correctArray.push(upperBound);
    arr.forEach((o, i, a) => {
        if (a[i] !== correctArray[i])
            return console.log(correctArray[i])
    })
}

this does log to console the value of 8,but I if use return correctArray[i] with console.log(findMissingNumber(arrayOfIntegers, 9, 3)) i get undefined , what is the cause of this?

Turqay Umudzade
  • 171
  • 2
  • 13

1 Answers1

0

Use .find instead of .forEach. Change the console.log to return true and return the result of the find.

return arr.find((o, i, a) => {
        if (a[i] !== correctArray[i])
            return true;
    })

You cannot return an enclosing function from within a lambda. You need to resolve to a value within the original function and return it from there.

Alternatively, use a simple for of loop instead of forEach.

Deadron
  • 5,135
  • 1
  • 16
  • 27
  • 1
    Maybe just `return a[i] !== correctArray[i]` would make more sense. Currently this works because you're returning the fasly value of `undefined` if the condition is false, but using `return a[i] !== correctArray[i]` would make that check more explicit – Nick Parsons Aug 13 '20 at 15:07
  • for some reason, this returns the answer+1? – Turqay Umudzade Aug 13 '20 at 15:12