Find the longest string

TypeScript
Easy

Objective

Write a function that returns the longest string in a given array

Requirements

  1. The function should be called findLongestString

  2. It takes a single parameter, which is an array of strings

  3. It should return the longest string in the array

  4. If the array is empty, it should return an empty string ''

  5. If multiple words have the same length, the function should return the first

  6. 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