Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
how can I output return only odd friends name from this array in JavaScript

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

In the oddFriend function, you are pushing the length of the name to the array instead of the name itself. Trying pushing name[i] instead.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

Your result is the number of chars (length of string) which is frName but you need each result to be the actual string which is name[i].

Corrected OP code

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

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

Fast and terse alternative

const array = ["jon", "james", "robert", "george", "Leo", "joy"];

let odd = array.flatMap(o => o.length % 2 === 1 ? [o] : []);

console.log(odd);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!