JavaScript Code

How to find the shortest string in array using JavaScript?


Problem Statement

given an array of strings, write a JavaScript program to find the shortest string in array

Solution

to find the shortest string in the given array of strings using JavaScript,

we use

Program

1. given array of strings is strArray. find the shortest string

function findShortestString(arr) {
  let shortest = "";
      if (arr.length == 0) {
          return null;
      } else {
          shortest = arr[0];
          for (let i = 1; i < arr.length; i++) {
              if ( shortest.length > arr[i].length ) {
                  shortest = arr[i];
              }
          }
          return shortest;
      }
}

strArray = ["apple", "banana", "bean", "pineapple"];
shortest = findShortestString(strArray);
console.log(shortest);


copyright @2022