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,
- 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);