How to use Array.reduce In Javascript
Using `Array.reduce`, iterate through the array, maintaining an accumulator array of the n largest elements. If an element is larger than any in the accumulator or the accumulator’s length is less than n, add it, then sort and slice the result.
Example:
const array = [10, 5, 20, 8, 15];
const n = 3;
const largestElements = array.reduce((acc, curr) => {
if (acc.length < n || curr > acc[acc.length - 1]) {
acc.push(curr);
acc.sort((a, b) => b - a).slice(0, n);
}
return acc;
}, []);
console.log("Largest elements:", largestElements);
Output
Largest elements: [ 20, 15, 10, 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