How to get the longest string in an array using JavaScript ?
Last Updated :
02 Aug, 2023
In this article, the task is to get the longest string from the array. 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.
Approaches to Get the Longest String in an Array:
- using the .sort() method
- using the .reduce() method
- using JavaScript for loop
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
let arr = [
"A_Copmuter_Science_Portal" ,
"GeeksforGeeks" ,
"GFG" ,
"geeks" ,
];
function gfg_Run() {
return arr.sort( function (a, b) {
return b.length - a.length;
})[0];
}
console.log(gfg_Run());
|
Output
A_Copmuter_Science_Portal
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.
Example: This example implements the above approach.
Javascript
let arr = [
"A_Copmuter_Science_Portal" ,
"GeeksforGeeks" ,
"GFG" ,
"geeks" ,
];
function gfg_Run() {
return arr.reduce( function (a, b) {
return a.length > b.length ? a : b;
});
}
console.log(gfg_Run());
|
Output
A_Copmuter_Science_Portal
In this approach, we will use JavaScript for loop to traverse through the array and find the longest string comparing each element.
Example: This example implements the above approach.
Javascript
let arr = [
"A_Copmuter_Science_Portal" ,
"GeeksforGeeks" ,
"GFG" ,
"geeks" ,
];
function gfg_Run() {
let longestString = "" ;
for (let i = 0; i < arr.length; i++) {
if (
typeof arr[i] === "string" &&
arr[i].length > longestString.length
) {
longestString = arr[i];
}
}
return longestString;
}
console.log(gfg_Run());
|
Output
A_Copmuter_Science_Portal
Share your thoughts in the comments
Please Login to comment...