- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 ]
Advertisements