Given an array and a number n, we can find the n largest elements from the array using JavaScript.
We can find the n largest elements using the following approaches.
Approach 1: Using sort() Method
In this approach, we sort the array in descending order using the sort() method and then use slice() to extract the first n elements.
Example: In this example, we sort the array in descending order and retrieve the three largest elements.
const arr = [93, 17, 56, 91, 98, 33, 9, 38, 55, 78, 29, 81, 60];
const n = 3;
arr.sort((a, b) => b - a);
const largestElements = arr.slice(0, n);
console.log(largestElements);
Output
[ 98, 93, 91 ]
Approach 2: Using Math.max() and filter()
In this approach, we use Math.max() to find the largest element and filter() to remove the selected element from the array. This process is repeated until n largest elements are obtained.
Example: In this example, we use Math.max() and filter() to find the three largest elements.
function getNLargestElements(arr, n) {
const largestElements = [];
for (let i = 0; i < n; i++) {
const max = Math.max(...arr);
largestElements.push(max);
arr = arr.filter(num => num !== max);
}
return largestElements;
}
const array = [1, 8, 3, 5, 9, 2];
console.log(getNLargestElements(array, 3));
Output
[ 9, 8, 5 ]
Approach 3: Using reduce() Method
In this approach, we use the reduce() method to maintain an array containing the n largest elements. Each element is added to the accumulator, sorted in descending order, and the smallest element is removed when the accumulator exceeds the required size.
Example: In this example, we use reduce() to find the three largest elements.
const array = [10, 5, 20, 8, 15];
const n = 3;
const largestElements = array.reduce((acc, curr) => {
acc.push(curr);
acc.sort((a, b) => b - a);
if (acc.length > n) {
acc.pop();
}
return acc;
}, []);
console.log("Largest elements:", largestElements);
Output
Largest elements: [ 20, 15, 10 ]