[SOLVED] how can I output return only odd friends name from this array in JavaScript

Issue

I want to output as a string from this code. I just checked its length but I could not output as a string again like-(‘joy’, ‘james’;). I don’t know where is my problem with the output string. please help to solve this problem. thank you.

function oddFriend(name) {
  let oddFr = [];
  for (let i = 0; i < name.length; i++) {
    let frName = name[i].length;
    console.log(frName);
    if (frName % 2 != 0) {
      oddFr.push(frName);
    }
  }
  return oddFr;
}

console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));

Solution

You just need to check that the length of the name isn’t an even number, and then push the element into the output array, not the length of the element.

function oddFriend(list) {
  let oddFr = [];
  for (let i = 0; i < list.length; i++) {
    const len = list[i].length;
    if (len % 2 !== 0) {
      oddFr.push(list[i]);
    }
  }
  return oddFr;
}

console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));

You could also use filter for this.

function oddFriend(list) {
  return list.filter(name => {
    return name.length % 2 !== 0;
  });
}

console.log(oddFriend(["jon", "james", "robert", "george", "Leo", "joy"]));

Answered By – Andy

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *