Home > Blockchain >  Finding specific string is odd or even from an array JavaScript
Finding specific string is odd or even from an array JavaScript

Time:02-05

Here is am trying to find a 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);

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related