Home > Software engineering >  Find strings with words starting with specific character in an array
Find strings with words starting with specific character in an array

Time:11-17

If I have array of string like

const arrayOfString=["Ajay Choudhary","Charlli Chouhan","Kerri Cilce","Dalis Menary"];

How to get name which has startswith C and surname startswith C like my output will be

Ajay Choudhary
Charlli Chouhan
Kerri Cilce

I have tried below but it does not give expected output

const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"];

arrayOfString.forEach(element => {
  //console.log(element);
  if (element.startsWith("C")) {
    //console.log(element);
  }
  if (element.charAt(element.charAt(-1)).startsWith("C")) {
    console.log(element);
  }
});

CodePudding user response:

You can use simple regex to check if any of words starts with C:

const arrayOfString=["Ajay Choudhary","Charlli Chouhan","Kerri Cilce","Dalis Menary", "Karoline-Celvin Boobier"];

arrayOfString.forEach(element => {
    if (/\bC\w /.test(element)) {
      console.log(element);
    }
 });

CodePudding user response:

Filter on the letter. I assume all names will start with capital letter

Note: McCain will be included too.

const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"];

const cNames = arrayOfString.filter(name => name.includes("C"))
console.log(cNames)

If you want to avoid names like McCain, then you can split and filter on startsWith

const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary", "Noddy McCain"];

const cNames = arrayOfString
  .filter(name => name.split(" ")
    .some(name => name.startsWith("C"))); // either first or lastname(s) starts with letter C
console.log(cNames)

CodePudding user response:

I think, spliting words with space and then filtering base on starting with 'C' will do what you want.

here is what I did :

arrayOfString.filter(name=>name.split(' ').filter(n => n.startsWith('C')).length > 0)

const arrayOfString = ["Ajay Choudhary", "Charlli Chouhan", "Kerri Cilce", "Dalis Menary"];
const result = arrayOfString.filter(name=>name.split(' ').filter(n => n.startsWith('C')).length > 0)
console.log(result)

  • Related