Search code examples
javascriptarraysstringfilterstartswith

How to check two words of a string separately with Startswith etc. and filter it in Javascript


const people = [
      { first: 'John', last: 'Doe', year: 1991, continent: "North America" },
      { first: 'Jane', last: 'Doe', year: 1990, continent: "Americas" },
      { first: 'Jahn', last: 'Deo', year: 1986, continent: "Europe" },
      { first: 'Jone', last: 'Deo', year: 1992, continent: "North America" },
      { first: 'Jhan', last: 'Doe', year: 1989, continent: "Asia" },
      { first: 'Jeon', last: 'Doe', year: 1992, continent: "Europe" },
      { first: 'Janh', last: 'Edo', year: 1984, continent: "North America" },
      { first: 'Jean', last: 'Edo', year: 1981, continent: "North America"},
];

I am able to check first word of continent with StartsWith but I want to find out if I look for "Am" it returns "North America" and "South America".

This is how I do currently;

const continent = people.filter(e =>
                e.continent.startsWith("Am")
            );

This returns an empty []. I tried to use split("") but then it creates an array and I have an error startswith doesn't exist in array. How can I check the second word in the string if it includes the certain string? In the end, I want to keep only objects of the array include "America", "North America", "South America".


Solution

  • You can still use filter and split. Also use some. split will create a array then use some to find if any on the element in that array starts with the required matching characters.

    For example on split North America will be ['North','America'] and some will check if any element in this array satisfy the requirement , then it will return true

    const people = [{
        first: 'John',
        last: 'Doe',
        year: 1991,
        continent: "North America"
      },
      {
        first: 'Jane',
        last: 'Doe',
        year: 1990,
        continent: "Americas"
      },
      {
        first: 'Jahn',
        last: 'Deo',
        year: 1986,
        continent: "Europe"
      },
      {
        first: 'Jone',
        last: 'Deo',
        year: 1992,
        continent: "North America"
      },
      {
        first: 'Jhan',
        last: 'Doe',
        year: 1989,
        continent: "Asia"
      },
      {
        first: 'Jeon',
        last: 'Doe',
        year: 1992,
        continent: "Europe"
      },
      {
        first: 'Janh',
        last: 'Edo',
        year: 1984,
        continent: "North America"
      },
      {
        first: 'Jean',
        last: 'Edo',
        year: 1981,
        continent: "North America"
      },
    ];
    
    
    const continent = people.filter((e) => {
      const continentName = e.continent.split(' ');
      const startWith = continentName.some(item => item.startsWith("Am"));
      if (startWith) {
        return e
      }
    });
    
    console.log(continent);