How to use Math.max and filter() method In Javascript
The approach combines Math.max to find the maximum element and filter to remove each found maximum from the array iteratively until `n` largest elements are obtained. This strategy efficiently retrieves the desired elements from the array.
Example: In this example This function returns the n largest elements from an array using Math.max and filter, demonstrated with an example array and n value.
function getNLargestElementsWithFilter(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(getNLargestElementsWithFilter(array, 3));
Output
[ 9, 8, 5 ]
How to get n largest elements from array in JavaScript ?
Here in this article, we will see how we can find the n maximum element from the array using Javascript.
Example:
Input: arr = [1, 2, 3, 4, 5, 6], n = 3;
Output: 4, 5, 6
Explanation: Here we will see the 3 largest elements in the given array are 4, 5, 6.Input: arr = [5, 76, 32, 98, 52, 57] n = 2;
Output: 98 , 76
There are some common ways to find the solution, and we will learn both of them one by one:
Table of Content
- Brute Force Approach
- Using Math.max and filter() method
- Using Array.reduce
Contact Us