Start learning free

LESSON 219 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Long Words Only in JavaScript: Filter an Array with a Loop

Practice Read the full explanation

Given an array of strings words and an integer n, return the words that are longer than n characters.

A word must be strictly longer than n: a word with exactly n characters is left out. Keep the words in the order they have in words. If no word is long enough, the result is empty.

 

Example 1:

Input: words = ["apple", "kiwi", "banana", "fig"], n = 4
Output: ["apple", "banana"]
Explanation: apple has 5 characters and banana has 6. kiwi has exactly 4, so it is left out, and fig has only 3.

Example 2:

Input: words = ["hi", "to", "be"], n = 3
Output: []
Explanation: No word has more than 3 characters.

Example 3:

Input: words = ["go", "went", "gone", "went"], n = 3
Output: ["went", "gone", "went"]
Explanation: Every word longer than 3 characters is kept, a repeated one too, in its original order.

 

Constraints:

  • words has at least one word, and every word is made of lowercase English letters.
  • n is 0 or more.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in JavaScript, explained

    Problem overview

    The method longWords(words, n) receives an array of strings and a number. It returns a new array with the words that have more than n characters, in their original order.

    For words = ["apple", "kiwi", "banana", "fig"] and n = 4, the lengths are 5, 4, 6 and 3. Only "apple" and "banana" are longer than 4, so the result is ["apple", "banana"]. "kiwi" has exactly 4 characters and is left out.

    Approach

    This is a filter: look at each item once and keep the ones that pass a test. You collect the survivors in a new array and leave words unchanged. Because the loop visits the words from first to last and push adds at the end, the kept words come out in their original order without any extra work.

    Step by step

    1. Create an empty array named result. Use let to declare it.
    2. Loop over the words with for...of. It gives you each string directly, with no index to manage.
    3. Test the length. The condition is word.length > n. Strictly greater matters: with >=, a word of exactly n characters would slip in.
    4. Push the word onto result when the test passes.
    5. Return after the loop. If no word passed, result is still an empty array, which is the correct answer.

    Tracing the example

    Here is what the loop sees for words = ["apple", "kiwi", "banana", "fig"] and n = 4. Each row shows the word, its length, whether length > n holds, and what result contained just before that word was handled.

    wordlengthkept?result before
    apple5true[]
    kiwi4false["apple"]
    banana6true["apple"]
    fig3false["apple", "banana"]

    After "fig" the loop ends and the function returns ["apple", "banana"]. The array grows only on the rows where the test is true, and "kiwi", which sits exactly on the boundary, is skipped. Notice also that the input array is never modified: the words are copied by reference into a separate array, so the caller's words still has all four entries afterwards.

    The solution in JavaScript

    class Solution {
        longWords(words, n) {
            let result = [];
            for (let word of words) {
                if (word.length > n) {
                    result.push(word);
                }
            }
            return result;
        }
    }
    

    Two details are worth knowing. First, length on a string is a property, not a method: write word.length, not word.length(). Second, push changes the array it is called on. Declaring result with let is fine here, and const would work too, since the variable is never reassigned, only its contents change.

    The same filter can be written as words.filter(word => word.length > n). The explicit loop shows what filter does underneath.

    The number n is a plain parameter, so the same function answers different questions: n = 0 keeps everything, a large n keeps nothing, and n = 4 keeps the words of five or more letters. Because the test is a single comparison, the whole function costs one pass over the array, and each word's length is read in constant time.

    Edge cases and common mistakes

    • Using >= instead of >. For ["kiwi"] with n = 4 the answer must be an empty array.
    • Returning inside the loop. A return in the if would stop at the first long word and send back one string instead of an array.
    • Repeated words. They stay. ["go", "went", "gone", "went"] with n = 3 gives ["went", "gone", "went"].
    • n = 0. Every word has at least one letter, so every word is kept: ["ab", "cd"] gives ["ab", "cd"].

    Testing

    • ["apple", "kiwi", "banana", "fig"], n = 4 gives ["apple", "banana"].
    • ["hi", "to", "be"], n = 3 gives [].
    • ["go", "went", "gone", "went"], n = 3 gives ["went", "gone", "went"].
    • ["ab", "cd"], n = 0 gives ["ab", "cd"].
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free