w3resource

JavaScript: Find the longest string from a given array of strings

JavaScript Basic: Exercise-83 with Solution

Find Longest String in Array

Write a JavaScript program to find the longest string from a given array of strings.

Visual Presentation:

JavaScript: Find the longest string from a given array of strings.

Sample Solution:

JavaScript Code:

// Function to find the longest string(s) in an array
function longest_string(str_ara) {
  var max = str_ara[0].length; // Initialize max length with the length of the first string
  str_ara.map(v => max = Math.max(max, v.length)); // Update max with the maximum length in the array using the map function
  result = str_ara.filter(v => v.length == max); // Filter out strings that have the maximum length
  return result; // Return the array of longest strings
}	

// Example usage
console.log(longest_string(['a', 'aa', 'aaa', 'aaaaa', 'aaaa']));  

Output:

["aaaaa"]

Live Demo:

See the Pen javascript-basic-exercise-83 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Find the longest string from a given array of strings

ES6 Version:

// ES6 version with comments

// Function to find the longest strings in an array
const longest_string = (str_ara) => {
    let max = str_ara[0].length; // Initialize max length with the length of the first string
    str_ara.map(v => max = Math.max(max, v.length)); // Update max by finding the maximum length in the array
    result = str_ara.filter(v => v.length == max); // Filter strings that have the maximum length
    return result; // Return the result array
};

// Example usage
console.log(longest_string(['a', 'aa', 'aaa', 'aaaaa', 'aaaa']));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript to add two positive integers without carry.
Next: JavaScript to replace each character of a given string by the next one in the English alphabet.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-83.php