

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return Top two elements from array JavaScript
We have an array of numbers in JavaScript that contains numbers in an unsorted order. Our job is to write a function that takes in this array of numbers and returns an array of two elements, the top two elements of the array (greatest two elements of the array).
We have to do this in one pass i.e., we need to execute this method in linear time like by using only one for loop or if we use ES6 function, we have to make sure to use only one and once and avoid nesting of methods which increases time complexity.
So, now let's write the code using the Array.prototype.reduce() method −
Example
const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3]; const topTwo = arr => { if(arr.length < 2){ return false; }; return arr.reduce((acc, val) => { if(val > acc[0]){ let t = acc[0]; acc[0] = val; acc[1] = t; }else if(val > acc[1]){ acc[1] = val; }; return acc; }, [-Infinity, -Infinity]); }; console.log(topTwo(arr));
Output
The output in the console will be −
[ 234, 87 ]
- Related Questions & Answers
- Return the sum of two consecutive elements from the original array in JavaScript
- Top n max value from array of object JavaScript
- Remove elements from array using JavaScript filter - JavaScript
- Removing redundant elements from array altogether - JavaScript
- Counting below / par elements from an array - JavaScript
- How to remove blank (undefined) elements from JavaScript array - JavaScript
- Add two consecutive elements from the original array and display the result in a new array with JavaScript
- Return the first duplicate number from an array in JavaScript
- JavaScript - How to pick random elements from an array?
- Picking the largest elements from multidimensional array in JavaScript
- Get unique item from two different array in JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript
- Return an array of all the indices of minimum elements in the array in JavaScript
- How do we access elements from the two-dimensional array in C#?
- Return the bases when first array elements are raised to powers from second array in Python
Advertisements