Get the max n values from an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a number, say n, as the second argument.

Our function should then pick the n greatest numbers from the array and return a new array consisting of those numbers.

Example

The code for this will be −

const arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52];
const pickGreatest = (arr = [], num = 1) => {
   if(num > arr.length){
      return [];
   };
   const sorter = (a, b) => b - a;
   const descendingCopy = arr.slice().sort(sorter);
   return descendingCopy.splice(0, num);
};
console.log(pickGreatest(arr, 3));
console.log(pickGreatest(arr, 4));
console.log(pickGreatest(arr, 5));

Output

And the output in the console will be −

[ 52, 30, 22 ]
[ 52, 30, 22, 20 ]
[ 52, 30, 22, 20, 18 ]
raja
Published on 23-Nov-2020 10:59:25
Advertisements