Home > Software design >  how can I output return only odd friends name from this array in JavaScript
how can I output return only odd friends name from this array in JavaScript

Time:02-05

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

CodePudding user response:

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.

CodePudding user response:

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, i) => {
    return name.length % 2 !== 0;
  });
}

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

CodePudding user response:

Sarah is right! Here's a complete example:

You are using a variable frName (this variable name needs to be improved to increase the code clarity) which in your question code example is holding the value of the name length.

You properly use that name length to check if the length is odd using the modulus operator, but you should push the original name parameter passed into the function instead of that value which is set to the name length.

function oddFriend(name) {
  let oddFriends = [];
  for (let i = 0; i < name.length; i  ) {
    let nameLength = name[i].length;

    if (nameLength % 2 !== 0) {
      oddFriends.push(name);
    }
  }

  return oddFriends;
}

CodePudding user response:

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

  •  Tags:  
  • Related