How to get n largest elements from array in JavaScript ?
Last Updated :
11 Jun, 2024
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:
Brute Force Approach
We will first make an array named largArr having a length equal to n. Then for each index of largArr, we will fill the element from the array one by one
Example: If we have n=3 then array largArr will be having a length equal to 3 then we will run for loop one by one to fill the element in the largArr.
JavaScript
let largArr = new Array();
let arr = new Array(93, 17, 56, 91,
98, 33, 9, 38, 55, 78, 29, 81, 60);
function largest() {
largArr[0] = 0;
largArr[1] = 0;
largArr[2] = 0;
for (i = 0; i < arr.length; i++) {
if (arr[i] > largArr[0]) {
largArr[0] = arr[i];
}
}
for (i = 0; i < arr.length; i++) {
if (arr[i] > largArr[1]
&& arr[i] < largArr[0]) {
largArr[1] = arr[i];
}
}
for (i = 0; i < arr.length; i++) {
if (arr[i] > largArr[2]
&& arr[i] < largArr[1]) {
largArr[2] = arr[i];
}
}
console.log(largArr[0]);
console.log(largArr[1]);
console.log(largArr[2]);
}
largest();
Output:
98
93
91
Optimized Solution: We first sort the array in decreasing order and then we run the loop for the length equal to n and print the first n largest elements.
Example:
JavaScript
let largArr = new Array();
let arr = new Array(93, 17, 56, 91, 98,
33, 9, 38, 55, 78, 29, 81, 60);
findLargest3();
function findLargest3() {
arr.sort((a, b) => a < b ?
1 : a > b ? -1 : 0);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr.slice(0, 3));
}
Output:
98
93
91
[98,93,91]
Using Math.max and filter() method
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.
JavaScript
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));
Using Array.reduce
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:
JavaScript
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);
OutputLargest elements: [ 20, 15, 10, 8, 5 ]
Similar Reads
JavaScript - Find Index of a Value in Array Here are some effective methods to find the array index with a value in JavaScript.Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. JavaScriptconst a = [10, 20, 30, 40, 50]; // Find index of value 30 const index = a.inde
2 min read
JavaScript - How to Get First N Elements from an Array? There are different ways to get the first N elements from array in JavaScript.Examples:Input:arr = [1, 2, 3, 4, 5, 6], n = 3 Output: [1, 2, 3] Input:arr = [6, 1, 4, 9, 3, 5, 7], n = 4Output: [6, 1, 4, 9]1. Using slice() MethodThe slice() method is used to extract a part of an array and returns a new
4 min read
How to Copy Array by Value in JavaScript ? There are various methods to copy array by value in JavaScript.1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.Syntax
4 min read
What is the most efficient way to concatenate N arrays in JavaScript ? In this article, we will see how to concatenate N arrays in JavaScript. The efficient way to concatenate N arrays can depend on the number of arrays and the size of arrays. To concatenate N arrays, we use the following methods:Table of ContentMethod 1: Using push() MethodMethod 2: Using concat() Met
3 min read
How to Merge Two Arrays and Remove Duplicate Items in JavaScript? Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor.1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to me
3 min read
How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
JavaScript - Check if JS Array Includes a Value? To check if an array includes a value we can use JavaScript Array.includes() method. This method returns a boolean value, if the element exists it returns true else it returns false.1. Using Array.includes() Method - Mostly Used The JS array.includes() method returns true if the array contains the s
4 min read
JavaScript - Create an Object From Two Arrays Here are the different methods to create an object from two arrays in JavaScript1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. JavaScriptconst a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi']; const res = {}; a1.forEac
3 min read
How to remove falsy values from an array in JavaScript ? Falsy/Falsey Values: In JavaScript, there are 7 falsy values, which are given below falsezero(0,-0)empty string("", ' ' , ` `)BigIntZero(0n,0x0n)nullundefinedNaNIn JavaScript, the array accepts all types of falsy values. Let's see some approaches on how we can remove falsy values from an array in Ja
6 min read
JavaScript - Use Arrays to Swap Variables Here are the different methods to swap variables using arrays in JavaScript1. Using Array DestructuringArray destructuring is the most efficient and modern way to swap variables in JavaScript. This method eliminates the need for a temporary variable.JavaScriptlet x = 5; let y = 10; [x, y] = [y, x];
3 min read