-2

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"]; 
sanaaa
  • 21
  • 1
  • See: [Does return stop a loop?](https://stackoverflow.com/q/11714503) - move the `return` after your `for` loop – Nick Parsons Apr 18 '23 at 09:36
  • Some of the words in 'x' is more than 4 letters. So maybe clarify your question and simplify it with input, actual output and expected output. – Steve Tomlin Apr 18 '23 at 09:37
  • Hi @SteveTomlin that is intentional for it to filter out everything but the 4 lettered names. – sanaaa Apr 18 '23 at 09:42
  • The reason your function doesn't work is because you are returning inside the for loop. It won't get to the 2nd increment because it returns after the first. Put your return after the for loop, before the last curly brace. – Steve Tomlin Apr 18 '23 at 09:49

2 Answers2

3

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

let x = ["Dustin", "Lily", "Steve", "Zed", "Mike"];
const result = x.filter((name) => name.length === 4);

console.log(result)

Hope this helps.

robert
  • 73
  • 7
  • _"What is the mistake I am doing?"_ – jabaa Apr 18 '23 at 10:02
  • You are returning the value before the for loop is finished. Alberto explained it here. https://stackoverflow.com/a/76043072/8731908 – robert Apr 18 '23 at 10:04
  • Yea. You're right, jabaa. I should have explained it. I basically just refactored the code. Thanks for flagging it! – robert Apr 18 '23 at 10:06
1

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.

 function friend(friends) {
      let result = [];
    
      for (let i = 0; i < friends.length; i++) {
        if (friends[i].length == 4) {
          result.push(friends[i]);
        }
      }
    
      return result;
    }
Alberto
  • 9
  • 3