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