Problem Statement
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);