Reputation: 1513
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]));
Upvotes: 1
Views: 70
Reputation: 19070
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]));
Upvotes: 3