- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the max n values from an array in JavaScript
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 ]
- Related Articles
- How to get the first n values of an array in JavaScript?
- Get max and min values of an array in Arduino
- Top n max value from array of object JavaScript
- Get n numbers from array starting from given point JavaScript
- Get max value per key in a JavaScript array
- Get the smallest array from an array of arrays in JavaScript
- Min and max values of an array in MongoDB?
- Select random values from an array in JavaScript?
- How to get only the first n% of an array in JavaScript?
- Extract unique values from an array - JavaScript
- Get the number of true/false values in an array using JavaScript?
- Get only specific values in an array of objects in JavaScript?
- Get average of every group of n elements in an array JavaScript
- Retrieve key and values from object in an array JavaScript
- Returning an array containing last n even numbers from input array in JavaScript

Advertisements