Skip to content
the poor coder

Codewars Find the smallest integer in the array

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC