JavaScript Program to Find the Largest Three Elements in an Array
Last Updated :
03 Jun, 2024
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.
Approaches to find the largest three elements in an array in JavaScript
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.
Example: This example demonstrated finding the largest three elements in an array by sorting the array and then picking the first three largest elements in JavaScript.
JavaScript
// Sort the array and then pick the
// first three largest elements
function findLargestThreeElementsUsingSort(arr) {
const sortedArrOutput = arr.sort((a, b) => b - a);
const [firstLargestEle, secondLargestEle,
thirdLargestEle] = sortedArrOutput.slice(0, 3);
return {
"First Largest Element in Array": firstLargestEle,
"Second Largest Element in Array": secondLargestEle,
"Third Largest Element in Array": thirdLargestEle,
};
}
const inputArray = [12, 56, 7, 89, 43, 21];
const outputElements =
findLargestThreeElementsUsingSort(inputArray);
console.log(outputElements);
Output{
'First Largest Element in Array': 89,
'Second Largest Element in Array': 56,
'Third Largest Element in Array': 43
}
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.
Example: This example demonstrated finding the largest three elements in an array by using loops to find the three largest elements in JavaScript.
JavaScript
//Using Loops
function largestThreeElements(arr) {
let firstLargestEle = arr[0];
let secondLargestEle = -Infinity;
let thirdLargestEle = -Infinity;
for (const num of arr) {
if (num > firstLargestEle) {
thirdLargestEle = secondLargestEle;
secondLargestEle = firstLargestEle;
firstLargestEle = num;
} else if (num > secondLargestEle) {
thirdLargestEle = secondLargestEle;
secondLargestEle = num;
} else if (num > thirdLargestEle) {
thirdLargestEle = num;
}
}
return {
"First Largest Element in Array": firstLargestEle,
"Second Largest Element in Array": secondLargestEle,
"Third Largest Element in Array": thirdLargestEle,
};
}
const inputArray = [12, 56, 7, 89, 43, 21];
const outputElements =
largestThreeElements(inputArray);
console.log(outputElements);
Output{
'First Largest Element in Array': 89,
'Second Largest Element in Array': 56,
'Third Largest Element in Array': 43
}
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.
Example: This example demonstrated finding the three largest elements in an array by using the 'Math.max' function to find the three largest elements in JavaScript.
JavaScript
//Using Math.max() function
function largestThreeElements(arr) {
const firstLargestEle = Math.max(...arr);
arr = arr.filter((num) => num !== firstLargestEle);
const secondLargestEle = Math.max(...arr);
arr = arr.filter((num) => num !== secondLargestEle);
const thirdLargestEle = Math.max(...arr);
return {
"First Largest Element in Array": firstLargestEle,
"Second Largest Element in Array": secondLargestEle,
"Third Largest Element in Array": thirdLargestEle,
};
}
const inputArray = [12, 56, 7, 89, 43, 21];
const outputElements =
largestThreeElements(inputArray);
console.log(outputElements);
Output{
'First Largest Element in Array': 89,
'Second Largest Element in Array': 56,
'Third Largest Element in Array': 43
}
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.
Example: This example demonstrates finding the largest three elements in an array by using a Min-Heap to maintain the three largest elements in JavaScript.
JavaScript
class MinHeap {
constructor() {
this.heap = [];
}
insert(val) {
this.heap.push(val);
this.bubbleUp();
}
bubbleUp() {
let index = this.heap.length - 1;
while (index > 0) {
let element = this.heap[index];
let parentIndex = Math.floor((index - 1) / 2);
let parent = this.heap[parentIndex];
if (parent <= element) break;
this.heap[index] = parent;
this.heap[parentIndex] = element;
index = parentIndex;
}
}
extractMin() {
const min = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this.sinkDown(0);
}
return min;
}
sinkDown(index) {
const length = this.heap.length;
const element = this.heap[index];
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIndex < length) {
leftChild = this.heap[leftChildIndex];
if (leftChild < element) {
swap = leftChildIndex;
}
}
if (rightChildIndex < length) {
rightChild = this.heap[rightChildIndex];
if ((swap === null && rightChild < element) || (swap !== null && rightChild < leftChild)) {
swap = rightChildIndex;
}
}
if (swap === null) break;
this.heap[index] = this.heap[swap];
this.heap[swap] = element;
index = swap;
}
}
size() {
return this.heap.length;
}
peek() {
return this.heap[0];
}
}
function findLargestThreeElementsUsingMinHeap(arr) {
const minHeap = new MinHeap();
for (let num of arr) {
if (minHeap.size() < 3) {
minHeap.insert(num);
} else if (num > minHeap.peek()) {
minHeap.extractMin();
minHeap.insert(num);
}
}
const [thirdLargestEle, secondLargestEle, firstLargestEle] = minHeap.heap.sort((a, b) => a - b);
return {
"First Largest Element in Array": firstLargestEle,
"Second Largest Element in Array": secondLargestEle,
"Third Largest Element in Array": thirdLargestEle,
};
}
const inputArray = [12, 56, 7, 89, 43, 21];
const outputElements = findLargestThreeElementsUsingMinHeap(inputArray);
console.log(outputElements);
Similar Reads
JavaScript Program to Find Top k Elements Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest). Table
4 min read
JavaScript Program to Find Largest Element in an Array In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array. Example: Input : [10, 15, 38, 20, 13];Output: 38H
3 min read
JavaScript Program to Find kth Largest/Smallest Element in an Array JavaScript allows us to find kth largest/smallest element in an array. We are given an array containing some elements, we have to find kth smallest/largest element from the array where k is a number greater than zero and less than equal to the total number of elements present in the array. There are
5 min read
C++ Program to Find the Second Largest Element in an Array In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
3 min read
JavaScript Program to find the Nth smallest/largest element from an unsorted Array In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It rep
4 min read
How to Find the Largest Element in an Array in PHP? Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases. Below are the approaches to find the largest element in an array in PHP:Table of ContentUsing max() FunctionUs
4 min read