I am trying to find an odd string from an given array.
Code :
const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];
function oddFriend(friendArray) {
for (let i = 0; i < friendArray.length; i++) {
if (friendArray[i].length % 2 != 0) {
return friendArray[i];
}
}
}
const myFriend = oddFriend(friendArray);
console.log(myFriend);
You can apply this:
const friendArray = ["agdum","bagdum","chagdum","lagdum","jagdum","magdum",];
function oddFriend(friendArray) {
if (friendArray.length % 2 != 0) {
return friendArray;
}
}
const myFriend = friendArray.filter(oddFriend);
console.log(myFriend);
.flatMap() and a ternary callback makes a simple and readable filter. It's not entirely clear if you wanted only odd or odd and even so there's both versions.
Odd length strings
const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];
let odd = fArray.flatMap(o => o.length % 2 === 1 ? [o] : []);
console.log(odd);
Odd & even length strings
const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];
let oe = [[], []];
fArray.forEach(o => o.length % 2 === 1 ? oe[0].push(o) : oe[1].push(o));
console.log(oe);
You can use Array.filter() method which will create a new array with all odd friends that pass the test implemented by the provided function.
// Input array
const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];
// Filtered result
console.log(friendArray.filter((friend) => friend.length % 2 !== 0));