JavaScript Exercises Basic#14 - Finding the Longest String from Array

JavaScript Exercises Basic#14 - Finding the Longest String from Array

You will be given an array with random strings. Write a program which returns the longest string from array.

Result Example Screenshot 2022-04-21 at 15.38.04.png Solution

  1. 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.
  2. 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.
  3. 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;
           }