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.
// 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