You will be given an array with random strings. Write a program which returns the longest string from array.
Result Example Solution
- We need a variable to store the longest element of the array. Let's call it 'max' and store the first element of the array for now. If we find a longer element, we'll replace it.
- Iterate through the array and compare the length of each element. If it's longer than whatever the value is in the variable 'max' now, replace it.
- Return 'max'.
function solution(arr){
let max = arr[0];
for (let i = 0; i < arr.length; i++){
if (arr[i].length > max.length){
max = arr[i];
}
}
return max;
}