How to usethe .sort() Method in Javascript

In this approach, we will use the sort() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. If the answer is positive then ‘b’ is greater else ‘a’ is greater. This method arranges the elements in the decreasing order of their length and we can access the first element by [0].

Example: This example implements the above approach. 

Javascript
// Input array of strings
let arr = [
    "A_Copmuter_Science_Portal",
    "w3wiki",
    "GFG",
    "geeks",
];

// It compares the length of an element with
// every other element and after sorting
// them in decreasing order it returns the
// first element.
function longestString() {
    return arr.sort(function (a, b) {
        return b.length - a.length;
    })[0];
}

// Display output
console.log(longestString());

Output
A_Copmuter_Science_Portal

How to Get the Longest String in an Array using JavaScript?

Given an array, the task is to get the longest string from the array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. In this article, we will use JavaScript methods to find out the longest string in the array. All approaches are described below with examples. 

Table of Content

  • Approach 1: Using the .sort() Method
  • Approach 2: Using the reduce() Method
  • Approach 3: Using JavaScript for Loop
  • Approach 4: Using the Math.max() and Spread Syntax

Similar Reads

Approach 1: Using the .sort() Method

In this approach, we will use the sort() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. If the answer is positive then ‘b’ is greater else ‘a’ is greater. This method arranges the elements in the decreasing order of their length and we can access the first element by [0]....

Approach 2: Using the reduce() Method

In this approach, we will use the reduce() method which calls a function on every 2 elements of the array. It takes ‘a’ and ‘b’ 2 arguments and compares their length. It returns the elements which have a length greater than every element....

Approach 3: Using JavaScript for Loop

In this approach, we will use JavaScript for loop to traverse through the array and find the longest string comparing each element....

Approach 4: Using the Math.max() and Spread Syntax

In this approach, we use the Math.max() function along with the spread syntax (…) to find the length of the longest string in the array. Then, we use the find() method to retrieve the longest string from the array based on its length....