skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search