How to use the sort() method In Javascript

In this approach we apply sort() method to array which will sort the array in ascending order. After sorting the largest element will be at the end of the array. We will return the last element which will be the largest element.

Syntax:

arr.sort((a, b) => a - b);
largestElement = arr[arr.length - 1];

Example: In this approach, we are using sort() method to find the largest number from our given array.

JavaScript
function findLargest(arr) {

    arr.sort((a, b) => a - b); // Sort the array in ascending order
    return arr[arr.length - 1]; // Return the last element
}

let arr = [10, 5, 20, 8];
console.log("Largest element in the array is:", findLargest(arr));

Output
Largest element in the array is: 20

JavaScript Program to Find Largest Element in an Array

In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array.

Example:

Input : [10, 15, 38, 20, 13];
Output: 38
Here we will see the 38 is the largest elements in the given array.

Several methods can be used to find the largest Element in an Array in Javascript, which are listed below:

Table of Content

  • Using the reduce() Method
  • Using the Spread Operator and Math.max() Method
  • Using for Loop
  • Using the sort() method
  • Using a ForEach Loop

Similar Reads

Using the reduce() Method

In this approach, Using the reduce() method, iterate through the array while comparing elements. Accumulate the largest element by updating the accumulator if the current element is greater. Return the largest element....

Using the Spread Operator and Math.max() Method

In this approach, the spread operator (…) with Math.max(), directly pass array elements as arguments, allowing the method to find and return the largest element in the array....

Using for Loop

In this approach, Using a for loop, iterate through the array, comparing each element to a running largest value, updating it if a larger element is encountered, and returning the final largest value....

Using the sort() method

In this approach we apply sort() method to array which will sort the array in ascending order. After sorting the largest element will be at the end of the array. We will return the last element which will be the largest element....

Using a ForEach Loop

Using a forEach loop iterates through the array, updating the largest element encountered. It initializes the largest element with the first element, then compares each subsequent element, updating the largest value accordingly....

Contact Us