Published on

Find smallest positive integer from array in Javascript

Authors

This article is about finding the smallest positive integer from an array.

Option 1

const arr = [1,4,53,9,10,43];
const sorted = arr.sort((a,b) => (a-b));
retrun sorted[0]; // 1

Option 1 looks clean but the time complexity of the above solution is O(n log(n)). There is a better way to achieve this. Check out option 2.

Option 2

const arr = [1, 4, 53, 9, 10, 43]

function findSmallest(_arr) {
  let smallest = _arr[0]

  for (let i = 0; i < _arr.length; i++) {
    if (_arr[i] < smallest) {
      smallest = _arr[i]
    }
  }

  return smallest
}

findSmallest(arr) // 1

Performance of Option 2 is better than Option 1. You can create this as a utility function in your project. Checkout this benchmark here.

Option 3

There is another option that we can use to find the smallest number. Nifty little trick. Credit goes to Louis St-Amour who reached out on LinkedIn with this option.

const arr = [1,4,53,9,10,43];
const sorted = arr.reduce((smallest, c) => c < smallest ? c : smallest);
retrun sorted; // 1

This uses Array.reduce method to reduce to the smallest number. Callback inside reduce method is called for each element in the array and keep track of the smallest number.