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 ]

Updated on: 31-Aug-2020

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements