how can I output return only odd friends name from this array in JavaScript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of how can I output return only odd friends name from this array in JavaScript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

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"]));
We are here to answer your question about how can I output return only odd friends name from this array in JavaScript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji