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 N Largest Elements from a Linked List
This JavaScript program is designed to identify the N largest elements from a linked list. A linked list is a linear data structure where elements, known as nodes, are connected via pointers. The program iterates through the linked list to determine the N largest elements it contains. Table of Conte
4 min read
Detecting the Largest Element in an Array of Numbers (nested) in JavaScript
Given a nested array of numbers, we need to find and return the largest element present in the array. Below are the approaches to detecting the largest element in an array of Numbers (nested) in JavaScript: Table of Content Iterative ApproachRecursive ApproachIterative ApproachUse a nested loop to t
3 min read
JavaScript Program to find Smallest Difference Triplet from Three Arrays
The article is about finding the smallest difference triplet from three arrays in JavaScript. Given three sorted arrays, we need to find three elements (one from each array) such that the difference between the maximum and minimum among the three is minimized. In other words, we are looking for a tr
4 min read
JavaScript Program to Find Largest Subarray with a Sum Divisible by k
Finding the largest subarray with a sum divisible by a given integer 'k' is a common problem in JavaScript and other programming languages. This task involves identifying a contiguous subarray within an array of integers such that the sum of its elements is divisible by 'k' and is as long as possibl
5 min read
JavaScript Program to Find Largest Number in a Linked List
Finding the largest number in a linked list is a common problem and can be efficiently solved using both iterative and recursive approaches. A linked list is a fundamental data structure where each element, known as a node, is connected to the next one, forming a chain. Table of Content Iterative Ap
3 min read
JavaScript Program to Construct Largest Number from Digits
In this article, we have given a set of digits, and our task is to construct the largest number generated through the combination of these digits. Below is an example for a better understanding of the problem statement. Example: Input: arr[] = {4, 9, 2, 5, 0}Output: Largest Number: 95420Table of Con
3 min read
JavaScript Program for K-th Largest Sum Contiguous Subarray
In this article, we are going to learn about K-th Largest Sum Contiguous Subarray in JavaScript. K-th Largest Sum Contiguous Subarray refers to finding the K-th largest sum among all possible contiguous subarrays within a given array of numbers, It involves exploring different subarray lengths and p
7 min read
Maximum of all Subarrays of Size k using JavaScript
This problem is about finding the biggest number in all groups of k adjacent numbers in an array. In JavaScript, you'd go through the array, looking at each group of k numbers at a time, and picking out the biggest one. This task is pretty common and is useful for things like analyzing data or optim
5 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