How to Get the Longest String in an Array using JavaScript?
Last Updated :
04 Jul, 2024
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.
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].
Example: This example implements the above approach.
JavaScript
// Input array of strings
let arr = [
"A_Copmuter_Science_Portal",
"GeeksforGeeks",
"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());
OutputA_Copmuter_Science_Portal
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.
Example: This example implements the above approach.
JavaScript
// Input array of strings
let arr = [
"A_Copmuter_Science_Portal",
"GeeksforGeeks",
"GFG",
"geeks",
];
// It compares the length of a element with
// every other element and return it if its
// greater than every other element.
function longestString() {
return arr.reduce(function (a, b) {
return a.length > b.length ? a : b;
});
}
// Display output
console.log(longestString());
OutputA_Copmuter_Science_Portal
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.
Example: This example implements the above approach.
JavaScript
// Input array of strings
let arr = [
"A_Copmuter_Science_Portal",
"GeeksforGeeks",
"GFG",
"geeks",
];
// It compares the length of a string with
// every other string and return it if its
// greater than every other string.
function longestString() {
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;
}
// Display output
console.log(longestString());
OutputA_Copmuter_Science_Portal
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.
Example:
JavaScript
// Input array of strings
let arr = [
"A_Copmuter_Science_Portal",
"GeeksforGeeks",
"GFG",
"geeks",
];
// Function to get the longest string in the array
function longestString() {
// Find the length of the longest string in the array
let maxLength = Math.max(...arr.map(str => str.length));
// Find the first string in the array with the maximum length
return arr.find(str => str.length === maxLength);
}
// Display output
console.log(longestString());
OutputA_Copmuter_Science_Portal
Approach 5: Using the filter() Method
In this approach, we will first find the length of the longest string in the array using the map() method and the Math.max() function. Then, we use the filter() method to create a new array containing only the strings with this maximum length. Finally, we return the first element from this filtered array.
Example: In this example, we utilize the filter() method to create a subset of the array containing only the strings that have the maximum length, and then simply return the first element from this subset. This method ensures that even if there are multiple strings with the maximum length, we can handle them efficiently.
JavaScript
// Input array of strings
let arr = [
"A_Copmuter_Science_Portal",
"GeeksforGeeks",
"GFG",
"geeks",
];
// Function to get the longest string in the array
function longestString() {
// Find the length of the longest string in the array
let maxLength = Math.max(...arr.map(str => str.length));
// Filter the array to get all strings with the maximum length
let longestStrings = arr.filter(str => str.length === maxLength);
// Return the first string with the maximum length
return longestStrings[0];
}
// Display output
console.log(longestString());
OutputA_Copmuter_Science_Portal
Using forEach
Using forEach to find the longest string in an array involves initializing a variable to store the longest string, then iterating through the array. For each string, compare its length to the current longest string, updating the variable if a longer string is found.
Example: In this example we are following above explained approach.
JavaScript
const getLongestString = (arr) => {
let longest = '';
arr.forEach(str => {
if (str.length > longest.length) {
longest = str;
}
});
return longest;
};
const strings = ["HTML", "CSS", "Javascript"];
console.log(getLongestString(strings));
Similar Reads
How to Get the Size of an Array in JavaScript
To get the size (or length) of an array in JavaScript, we can use array.length property. The size of array refers to the number of elements present in that array. Syntaxconst a = [ 10, 20, 30, 40, 50 ] let s = a.length; // s => 5 The JavaScript Array Length returns an unsigned integer value that
2 min read
How to check a string data type is present in array using JavaScript ?
In JavaScript, an array is a collection of data that can be of the same or different type. If we have the array containing the data, our task is to identify if it is a string data type. In this article, we will learn how to use the typeof operator. Syntax: typeof value Note: The typeof operator retu
3 min read
JavaScript - How To Get The Last Caracter of a String?
Here are the various approaches to get the last character of a String using JavaScript.1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1.JavaScriptconst s = "JavaScript"; co
3 min read
How to Get the Length of a String in Bytes in JavaScript ?
In JavaScript, determining the length of a string in characters is straightforward using the length property. However, in many cases, particularly when dealing with file sizes, network protocols, or database storage, you might need to know the length of a string in bytes. This is because characters
3 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of ContentApproach 1: using JavaScript array.map() and toString() methodsApproach 2: Us
2 min read
How to find the longest word within the string in JavaScript ?
To find the longest word within the string in JavaScript we will compare the counts to determine which word has the most characters and return the length of the longest word. Example: Input: "This is a demo String find the largest word from it"Output: "largest"Input: "Hello guys this is geeksforgeek
6 min read
How to Find the Length of an Array in JavaScript ?
JavaScript provides us with several approaches to count the elements within an array. The length of an array lets the developer know whether an element is present in an array or not which helps to manipulate or iterate through each element of the array to perform some operation. Table of Content Usi
3 min read
JavaScript - How to Pad a String to Get the Determined Length?
Here are different ways to pad a stirng to get the specified length in JavaScript.1. Using padStart() MethodThe padStart() method can be used to pad a string with the specified characters to the specified length. It takes two parameters, the target length, and the string to be replaced with. If a nu
3 min read
How to create a string by joining the elements of an array in JavaScript ?
Given an array containing array elements and here we will join all the array elements to make a single string. To join the array elements we use arr.join() method. There are two methods by which we can create a string by joining the elements of an array: Table of Content Using arr.join() MethodUsing
2 min read
How to Truncate an Array in JavaScript?
Here are the different methods to truncate an array in JavaScript1. Using length PropertyIn Array.length property, you can alter the length of the array. It helps you to decide the length up to which you want the array elements to appear in the output.JavaScriptconst n = [1, 2, 3, 4, 5, 6]; n.length
4 min read