Find the longest string
TypeScript
Easy
Objective
Write a function that returns the longest string in a given array
Requirements
The function should be called
findLongestString
It takes a single parameter, which is an array of strings
It should return the longest string in the array
If the array is empty, it should return an empty string
''
If multiple words have the same length, the function should return the first
The function should be written in TypeScript
Check your solution
Tests
Function name is findLongestString | |||
findLongestString(["one","two","three"]) | Expected: | "three" | |
findLongestString(["lorem","ipsum","dolor","sit","amet"]) | Expected: | "lorem" | |
findLongestString([]) | Expected: | "" |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function findLongestString (array: string[]): string {
let longest = '';
for (let i = 0; i < array.length; i++) {
if (array[i].length > longest.length) {
longest = array[i];
}
}
return longest;
}
Click to reveal