Home > Software engineering >  Filtering out a name starting with letter 'P' from Array of objects using typescript
Filtering out a name starting with letter 'P' from Array of objects using typescript

Time:10-27

Here's my code:

const names = [
    {name:'Finn',age: 23},
    {name:'Presten',age: 24},
    {name:'Pearl',age: 21},
    {name:'Tim',age: 22},
    {name:'Jade',age: 25},
    {name:'Princess',age: 23},
] 
const filterName = names.filter(function(nameWithOutC: {name: string, age: number}): boolean {
    return nameWithOutP.book !== 'P'
})

console.log('Filtering out a name starting with letter P')
console.log(filterName)

I am trying to figure out how can able to filter out the names starting with the letter "P".

CodePudding user response:

You can use something like this to get rid of strings starting with the letter "P":

bookstore.filter((name, age) => !name.startsWith("P"))

Or this to only keep strings with the starting letter "P":

bookstore.filter((name, age) => name.startsWith("P"))

CodePudding user response:

by placing search you can search for any word in the string, of course using the filter method, you can also negate it:

!name.search("P")

const names = [
        { name: "Finn", age: 23 },
        { name: "Presten", age: 24 },
        { name: "Pearl", age: 21 },
        { name: "Tim", age: 22 },
        { name: "Jade", age: 25 },
        { name: "Princess", age: 23 }
      ];
      const filterName = names.filter(({ name }) => name.search("P"));
    
      console.log("Filtering out a name starting with letter P");
      console.log(filterName);

  • Related