How to use Sorting() Method In Javascript
In this approach, we sort the given array in descending or ascending order and return the element at the N-1 index.
Follow the given steps to solve the problem (Nth Smallest):
- Sort the input array in ascending order.
- Return the element at the N-1 index in the sorted array(0 – Based indexing).
Follow the given steps to solve the problem (Nth Largest):
- Sort the input array in the descending order.
- Return the element at the N-1 index in the sorted array (0 – Based indexing).
Syntax:
array.sort();
Example: Below is the implementation of the above approach.
let arr = [1, 3, 2, 4, 8, 7, 5, 6];
let n = 3;
let largest = (arr, n) => {
arr.sort((a, b) =>
b - a); return arr[n - 1]
};
let smallest = (arr, n) => {
arr.sort((a, b) =>
a - b); return arr[n - 1]
};
console.log("N'th Largest ", largest(arr, n));
console.log("N'th Smallest ", smallest(arr, n));
Output
N'th Largest 6 N'th Smallest 3
JavaScript Program to find the Nth smallest/largest element from an unsorted Array
In this article, we will see how to find Nth largest and smallest element from an unsorted array. The Nth smallest/largest element from an unsorted array refers to the element that ranks at the Nth position when the array is sorted either in ascending (smallest) or descending (largest) order. It represents the value at the Nth position when considering all unique values in the array.
Examples:
Input:
arr[]={1, 3, 2, 4, 8, 7, 5, 6},
N=3
Output:
largest=6,
smallest=3
There are several methods that can be used to find the Nth smallest/largest element from an unsorted Array in JavaScript, which are listed below:
Table of Content
- Using Sorting() Method
- Using Set() Method
- Using Quickselect Algorithm
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us