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,
- initialize the
shortest
with the first string in array - iterate over items of the array using a for loop
- if the current element is smaller in length than that of the
shortest
, updateshortest
with the current element
- if the current element is smaller in length than that of the
we use
- String.length to get the length of a string
- greater than comparison operator to check if the length of
shortest
is greater than the length of the current element in array
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);