Find the longest string in array in JavaScript
In this tutorial, you are given an array of strings. Write a JavaScript program to find the longest string in array.
Solution
To find the longest string in the given array of strings using JavaScript,
- Initialize the
longest
with the first string in array. - Iterate over items of the array using a for loop
- if the current element is largest in length than that of the
longest
, updatelongest
with the current element.
- if the current element is largest in length than that of the
We use
- String.length to get the length of a string.
- Less than comparison operator to check if the length of
longest
is less than the length of the current element in array.
Program
1. Given array of strings is strArray
. Find the longest string.
function findLongestString(arr) {
let longest = "";
if (arr.length == 0) {
return null;
} else {
longest = arr[0];
for (let i = 1; i < arr.length; i++) {
if ( longest.length < arr[i].length ) {
longest = arr[i];
}
}
return longest;
}
}
strArray = ["apple", "banana", "pineapple", "bean"];
longest = findLongestString(strArray);
console.log(longest);