1

I have a simple algorithm I'm working on, return the smallest number using recursion. Everything seems to be right and working, except that when I return the numbers array at the end, it comes back as undefined.

function findSmallestInt(numbers) {
  var updatedArr = [];
  if (numbers[0] < numbers[1]) {
    numbers.splice(1, 1);
    if (numbers.length > 1) {
      findSmallestInt(numbers);
    } else {
      return numbers;
    }
  } else {
    numbers.splice(0, 1);
    if (numbers.length > 1) {
      findSmallestInt(numbers);
    } else {
      return numbers;
    }
  }
}

console.log(findSmallestInt([78, 56, 232, 12, 18]));
1
  • 7
    You forgot to return the recursive calls Commented Mar 20, 2019 at 4:49

1 Answer 1

3

You can use Math.min():

console.log([Math.min(...[78, 56, 232, 12, 18])]);

And for your recursive function, as previously pointed out in the comments by @CertainPerformance, you should return the findSmallestInt(number) function result:

function findSmallestInt(numbers) {
  numbers.splice(numbers[0] < numbers[1] ? 1 : 0, 1);
  return numbers.length > 1 ? findSmallestInt(numbers) : numbers;
}

console.log(findSmallestInt([78, 56, 232, 12, 18]));

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

Comments

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.