How to use sort() Method In Javascript
The Javascript array.sort() is an inbuilt method in JavaScript that is used to sort the array. An array can be of any type i.e. string, numbers, characters, etc. Here array is the set of values that are going to be sorted.
Syntax:
array.sort()
Example:
function LargestElement(arr) {
if (arr.length === 0) {
console.log("Array is empty");
}
arr.sort((a, b) => b - a);
return arr[0];
}
const arr = [22, 65, 1, 39];
console.log("Largest in given array is " + LargestElement(arr));
Output
Largest in given array is 65
Javascript Program to Find the Largest Element in an Array
Finding the largest element in an array is a common task in JavaScript, useful in various scenarios such as data analysis, sorting, and mathematical computations. This article explores several methods to efficiently determine the largest element, ensuring robust and optimized solutions for your coding needs. Let’s first see simple examples input and output.
Examples:
Input: arr = [10, 20, 4]
Output: 20
Explanation: Among 10, 20 and 4, 20 is the largest.Input : arr = [20, 10, 20, 4, 100]
Output : 100
Contact Us