Codewars Find the smallest integer in the array
Codewars: Find the smallest integer in the array
If you're like me, then you've probably done your fair share of coding challenges on websites like Codewars. This particular challenge asks you to write a function that takes an array of integers and returns the smallest integer in the array. Let's take a look at how we might solve this problem.
Approach 1: Using Math.min() and the spread operator
One simple way to solve this problem is to use the built-in Math.min() function along with the spread operator to find the smallest integer in the array. Here's what the code might look like:
function findSmallestInt(arr) {
return Math.min(...arr);
}
Here, we're simply passing the array of integers to Math.min() using the spread operator (...), which allows us to pass individual elements of an array as arguments to a function. Math.min() then returns the smallest integer in the array.
Approach 2: Using a for loop
Another approach is to use a for loop to iterate over the array and keep track of the smallest integer as we go. Here's what the code might look like:
function findSmallestInt(arr) {
let smallestInt = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < smallestInt) {
smallestInt = arr[i];
}
}
return smallestInt;
}
Here, we start by setting the initial value of smallestInt to the first element of the array. We then loop over the rest of the array, comparing each element to smallestInt and updating smallestInt if we find a smaller element. Finally, we return smallestInt.
Conclusion
Both of these approaches will work to solve the Codewars challenge of finding the smallest integer in an array. Which one you choose will depend on your personal coding style and preferences. Happy coding!