Approaches to find the largest three elements in an array in JavaScript

Table of Content

  • Using JavaScript sort() Method
  • Using JavaScript loops
  • Using JavaScript Math.max() Method
  • Using a Min-Heap (Priority Queue)

JavaScript Program to Find the Largest Three Elements in an Array

In this article, we are given an array of numbers, we need to find the largest three elements in an array in JavaScript. We will explore the easiest and most efficient code of each approach and also go through the output of the code.

Similar Reads

Approaches to find the largest three elements in an array in JavaScript

Table of Content Using JavaScript sort() MethodUsing JavaScript loopsUsing JavaScript Math.max() MethodUsing a Min-Heap (Priority Queue)...

Using JavaScript sort() Method

First, we will sort the array in descending order. We will use the sort() function to sort the array, once the sorting is completed, the largest elements will be at the start of the array. Using the slice() method, we will extract the first three elements which are the three largest elements in the array....

Using JavaScript loops

Here, we will use the JavaScript loop to iterate through the array of elements once. We will keep three variables as (‘firstLargestEle’, ‘secondLargestEle’, and ‘thirdLargestEle’. Firstly, we will initialize the ‘firstLargestEle‘ to the first element of the input array and ‘secondLargestEle‘, and ‘thirdLargestEle‘ to the negative infinity which is used to handle the negative numbers. Later, we will apply the comparision logic in the loop and return the three largest elements from the array....

Using JavaScript Math.max() Method

Here, like in Approach 2, rather than having three variables, we will use the Math.max() function to iterate and find the three largest elements....

Using a Min-Heap (Priority Queue)

In this approach, we use a Min-Heap (Priority Queue) to keep track of the largest three elements as we iterate through the array. The idea is to maintain a heap of size 3. For every element in the array, we check if it’s larger than the smallest element in the heap (the root of the Min-Heap). If it is, we remove the smallest element and insert the current element into the heap....

Contact Us