Start learning free

LESSON 223 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Lengths in TypeScript: Mapping Strings to Numbers

Practice Read the full explanation

Given an array of strings words, return an array of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in TypeScript, explained

    Problem overview

    The method wordLengths receives an array of strings, words, and returns an array of numbers: the length of each word, in the same order.

    For ["I", "love", "pancakes"] the answer is [1, 4, 8]. One word gives one length, so ["code"] gives [4]. Words can contain uppercase letters, and they count like any other: ["Hello", "WORLD"] gives [5, 5].

    Approach

    Each word produces exactly one number, so the output has as many items as the input. Visit the words from first to last, compute word.length for each, and add it to the end of a new array. Adding at the end is what keeps the order.

    Here is the loop on ["I", "love", "pancakes"]. Round one pushes 1, round two pushes 4, round three pushes 8, and lengths grows from [] to [1], [1, 4] and finally [1, 4, 8]. The array is built up one item per word, which is the basic shape of most loops that produce a list: create an empty collection, add to it inside the loop, return it afterwards.

    This shape also differs from a filter such as keeping only the long words. A filter pushes inside an if and can end with fewer items than it started with. Here there is no if, so every word contributes, and the result is always exactly as long as words.

    Step by step

    1. Start with an empty array of numbers. lengths, typed number[], collects the results.
    2. Loop over the words with for (const word of words). The loop runs once per word.
    3. Push the length. word.length goes onto lengths.
    4. Return after the loop. Put return lengths below the closing brace of the loop. Inside it, only the first length would come back.

    The solution in TypeScript

    class Solution {
        wordLengths(words: string[]): number[] {
            let lengths: number[] = [];
            for (const word of words) {
                lengths.push(word.length);
            }
            return lengths;
        }
    }
    

    Details worth knowing:

    • Two different arrays. The parameter is a string[] and the result is a number[]. Their types differ, but they have the same length.
    • length has no parentheses. It is a property of strings and arrays. Writing word.length() is a type error, and if the JavaScript ran anyway it would fail, because a number can't be called.
    • Types are erased. After compilation the annotations are gone; push and length are plain JavaScript.

    The one-line version is words.map(word => word.length). The loop does the same work and makes each step visible.

    Strings and arrays both have length, so the same property answers two different questions in this lesson. On words it counts the words; on word it counts the letters. Knowing which variable you are asking keeps the two apart.

    Edge cases and common mistakes

    • Returning inside the loop. The result would hold one number at most.
    • Counting words instead of letters. words.length is how many words there are. The length of one word is word.length.
    • Case. "WORLD" has 5 letters just as "world" does. Nothing needs converting.
    • Order. Pushing in loop order keeps it. Sorting the result would break the match between lengths and words.

    Testing

    • ["I", "love", "pancakes"] gives [1,4,8].
    • ["banana", "kiwi", "fig"] gives [6,4,3].
    • ["code"] gives [4].
    • ["Hello", "WORLD"] gives [5,5].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free