 Open in App
Not now

# How to get n largest elements from array in JavaScript ?

• Difficulty Level : Easy
• Last Updated : 09 Dec, 2022

Here in this article, we will see that 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 two ways to find out the solution, 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

 ``

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

 ``

Output:

``` 98
93
91
[98,93,91]```

My Personal Notes arrow_drop_up
Related Articles