find the smallest element in array in javascript

To find the smallest element in an array in JavaScript, you can use a loop to iterate through the array and keep track of the current minimum value. Here is an example function:

index.tsx
function findSmallest(arr) {
  let min = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) {
      min = arr[i];
    }
  }
  return min;
}
160 chars
10 lines

This function starts by assuming that the first element of the array is the minimum. It then iterates through the remaining elements of the array and compares each one to the current minimum. If it finds a smaller value, it updates the minimum. Finally, it returns the smallest value it found.

You can call this function with any array of numbers:

index.tsx
let numbers = [7, 2, 9, 3, 1];
let smallest = findSmallest(numbers);
console.log(smallest); // Outputs 1
105 chars
4 lines

gistlibby LogSnag