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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read