Search code examples
javascriptlodash

JavaScript find first number in array that is <= to given number


I have an array of prime numbers:

const primes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

I want to find the first number in this list that is <= the number given.

For example ... getHighestPrimeNumber(58) ... should return 53, being the prime number with the greatest value which is also less than or equal to 58

Expect results:

getHighestPrimeNumber(58) === 53

getHighestPrimeNumber(53) === 53

getHighestPrimeNumber(52) === 47

My current approach is to iterate through the prime numbers but this is very inefficient, especially given that there may be 10,000+ numbers in the list - thanks

Vanilla JS or Lodash is fine


Solution

  • Since you posted this with lodash tag just FYI that this with it is trivial due to _.sortedIndex:

    const primes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
    
    const closestPrime = (n) => {
      let index = _.sortedIndex(primes, n)
      return primes[index] == n ? primes[index] : primes[index-1]
    }
    
    console.log(closestPrime(58))
    console.log(closestPrime(53))
    console.log(closestPrime(52))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>