JavaScript Code


How to find the shortest string in array using JavaScript?


Find the shortest string in array in JavaScript

In this tutorial, you are 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