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

Why Find the Largest Element?

Identifying the largest element in an array is essential for:

  • Data analysis and statistical calculations.
  • Implementing algorithms that require maximum value identification.
  • Enhancing application features that depend on peak values, such as leaderboards and maximum thresholds.

Below are the following approaches through which we find the largest element in an array in JavaScript:

Table of Content

  • 1. Using Brute force Approach
  • 2. Using Math.max() and apply() Methods
  • 3. Using reduce() Method
  • 4. Using sort() Method
  • 5. Using Recursion
  • 6. Using the forEach Method
  • 7. Using the Spread Operator

1. Using Brute force Approach

  • Create a local variable max and initiate it to arr[0] to store the maximum among the list
  • Initiate an integer i = 0 and repeat steps 3 to 5 till i reaches the end of the array.
  • Compare arr[i] with max.
  • If arr[i] > max, update max = arr[i].
  • Increment i once.
  • After the iteration is over, return max as the required answer.

Example:

Javascript
// JavaScript program to find
// maximum in arr[] of size n

function largest(arr) {
    let i;

    // Initialize maximum element
    let max = arr[0];

    // Traverse array elements
    // from second and compare
    // every element with current max
    for (i = 1; i < arr.length; i++) {
        if (arr[i] > max)
            max = arr[i];
    }

    return max;
}

// Driver code
let arr = [22, 65, 1, 39];
console.log("Largest in given array is " + largest(arr));

Output
Largest in given array is 65

2. Using Math.max() and apply() Methods

The JavaScript Math max() Method is used to return the largest of zero or more numbers. The result is “-Infinity” if no arguments are passed and the result is NaN if at least one of the arguments cannot be converted to a number. The apply() function allows you to pass an array of arguments to the Math.max() function.

Syntax:

Math.max(value1, value2, ...)

Example:

Javascript
function LargestElement(arr) {
    if (arr.length === 0) {
        console.log("Array is empty");
    }

    return Math.max.apply(null, arr);
}
const arr = [22, 65, 1, 39];
console.log("Largest in given array is " + LargestElement(arr));

Output
Largest in given array is 65

3. Using reduce() Method

The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Syntax: 

array.reduce( function(total, currentValue, currentIndex, arr), 
initialValue )

Example:

Javascript
function LargestElement(arr) {
    if (arr.length === 0) {
        console.log("Array is empty");
    }

    return arr.reduce(function (a, b) {
        return (a > b) ? a : b});

}
const arr = [22, 65, 1, 39];
console.log("Largest in given array is " + LargestElement(arr));

Output
Largest in given array is 65

4. Using sort() Method

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:

Javascript
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

5. Using Recursion

  • Create a recursive function.
  • Set an integer i = 0 to denote the current index being searched.
  • Return steps 4 to 7 to get the final answer.
  • If i is the last index, return arr[i].
  • Increment i and call the recursive function for the new value of i.
  • Compare the maximum value returned from the recursion function with arr[i].
  • Return the max between these two from the current recursion call.

Example:

Javascript
// JS program to find maximum
// in arr[] of size n
function largest(arr, n, i) {
    // last index
    // return the element
    if (i == n - 1) {
        return arr[i];
    }

    // find the maximum from rest of the array
    let recMax = largest(arr, n, i + 1);

    // compare with i-th element and return
    return Math.max(recMax, arr[i]);
}

// Driver Code
const arr = [22, 65, 1, 39];
const n = arr.length;
console.log("Largest in given array is", largest(arr, n, 0));

Output
Largest in given array is 65

6. Using the forEach Method

The forEach method iterates over each element in the array, comparing each element to a variable (`max`) initialized to the first element. If the current element is greater than max, max is updated. After the loop, max holds the largest value.

Example: In this example The function findLargestWithForEach iterates through each element of the array using forEach and updates the max variable if it finds a number greater than the current maximum.

JavaScript
function findLargestWithForEach(arr) {
    let max = arr[0];
    arr.forEach(num => {
        if (num > max) {
            max = num;
        }
    });
    return max;
}

console.log(findLargestWithForEach([1, 2, 3, 4, 5])); 

Output
5

7. Using the Spread Operator

The spread operator (…) allows an iterable such as an array to be expanded in places where zero or more arguments or elements are expected. This operator can be used with Math.max() to find the largest element in the array.

Example:

JavaScript
function largestElementWithSpread(arr) {
    if (arr.length === 0) {
        console.log("Array is empty");
        return;
    }

    return Math.max(...arr);
}

const arr = [22, 65, 1, 39];
console.log("Largest in given array is " + largestElementWithSpread(arr));

Output
Largest in given array is 65


Finding the largest element in an array is a fundamental skill for JavaScript developers. By understanding and implementing these methods, you can handle a wide range of data manipulation tasks efficiently. This article focuses on essential concepts and practical examples to enhance your programming capabilities.



Contact Us