How to use sort() Method In Javascript
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.
// 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 }
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.