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"]));//[]