Functions/Arrays/String

Hello everyone. Can someone help me with this exercise? I don’t understand why only one element is added to the result when there are more elements in the array that meet the condition(if(arr[i].startsWith(str))

Thank you in advance

Create a function that takes an initial string and an array of words, and returns a filtered array of the words that start with the same letters as the initial string.

Notes:

  • If none of the words match, return an empty array.

  • Keep the filtered array in the same relative order as the original array of words.

Examples:

  • dictionary(“bu”, [“button”, “breakfast”, “border”]) ➞ [“button”]

  • dictionary(“tri”, [“triplet”, “tries”, “trip”, “piano”, “tree”]) ➞ [“triplet”, “tries”, trip"]

  • dictionary(“beau”, [“pastry”, “delicious”, “name”, “boring”]) ➞

const dictionary=(str,arr)=>{
        let resultArray=[];
        for(i=0;i<arr.length;i++){
            if(arr[i].startsWith(str)){
              resultArray.push(arr[i]);

            }
            return resultArray
        }  
    }
    
    console.log(dictionary("bu", ["button", "breakfast", "border"]));//[ 'button' ]
    console.log(dictionary("tri", ["triplet", "tries", "trip", "piano", "tree"]));//[ 'triplet' ]
    console.log(dictionary("beau", ["pastry", "delicious", "name", "boring"]));//[]

.startsWith() returns a string that starts with the string passed in. So, out of the array passed in, if one of the elements is button, and one is light bulb, and the string passed in is bu, button would be returned, since it is the string that actually starts with bu.
I hope this helps!

Hi @delafuentej
you return the result inside the for loop. That overwrites the new array with just one value each time the loop runs.
This returns the correct result:

const dictionary=(str,arr)=>{
        let resultArray=[];
        for(i=0;i<arr.length;i++){
            if(arr[i].startsWith(str)){
              resultArray.push(arr[i]);
            }
        }
        return resultArray;
    }
    
    console.log(dictionary("bu", ["button", "breakfast", "border"]));//[ 'button' ]
    console.log(dictionary("tri", ["triplet", "tries", "trip", "piano", "tree"]));//[ 'triplet' , 'tries', 'trip']
    console.log(dictionary("beau", ["pastry", "delicious", "name", "boring"]));//[]

That was the problem. Thank you very much for your help. Regards

You’re welcome. Just one remark as my explanation wasn’t a 100% correct: You exit the function after the first hit if you return the array inside the for loop. You don’t overwrite the array with one value as I initially wrote.

1 Like