Given below is the code I have written in attempt to create a function that finds all 4 letters in an array, places them onto a new one, and returns it.
Whenever I tried to run the code below, it doesn’t give all the 4 letters names, only the first one.
What is the mistake I am doing?
function friend(friends){
let result = [];
for (let i = 0; i < friends.length; i++){
if (friends[i].length == 4) {
result.push(friends[i]);
return result;
}
}
};
let x = ["Dustin", "Lily", "Steve", "Zed", "Mike"];
2
Answers
If I understood correctly you want an array with only the names that have 4 letters.
If that’s the case, you can use the filter function on the array of names to filter only the names that have 4 letters. Snippet below
Hope this helps.
This code seems to be incomplete, as the return statement is inside the for loop, which means that the function will exit and return the result array after checking the first string in the friends array that has a length of 4. If you want the function to return an array of all the strings in friends that have a length of 4, you should move the return statement outside the for loop.