Search code examples
javascriptnode.js

Shortest way to get prime numbers JS


Is there a way to get prime numbers in one line I was given a task to get the largest prime number in an array in one line is that even possible?!

Given an array of numbers. Create a function which returns the largest prime number. (​NOTE*​, 
it should be written only 1 line of code). ​(2)

let arr1 = [1,5,7,6,9,10,13,11,12]
    function largestPrime(arr) {
    // write your code here... }
    }


Solution

  • Referring the great answer of @Sergio to the question: Number prime test in JavaScript. You can filter the prime numbers in the array then get the largest one by using the Math.max function.

    let arr1 = [1,5,7,6,9,10,13,11,12]
        function largestPrime(arr) {
          return Math.max(...arr.filter((n) => { return ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n) }));
        }
      console.log(largestPrime(arr1));