Search code examples
angulartypescriptangular7typescript2.0

Filter an array with elements by first letter of each word


I have this code :

return !this.form.get('skills').value.map(item => item.id).includes(skill.id) &&
            (value === null || skill.name.toLowerCase().startsWith(value.toLowerCase()));

I have this liste :

Artist
Armagedon
Commandos Artist
Refactor
Gol Jumir Afart
Armony

If I write : A : I get the liste :

Artist
Armagedon
Armony

But I want to get and items : Commandos Artist and Gol Jumir Afart.

Can you help me please ?


Solution

  • You can use a Regexp in order to filter your values. We are going to look for every words starting by your letter.

    const myFilter = 'A';
    
    const regex = new RegExp(`(^${myFilter}.*)|( ${myFilter}.*)`, 'i');
    
    const filtered = [
      'Artist',
      'Armagedon',
      'Commandos Artist',
      'Commandos Artist Paul',
      'Refactor',
      'Gol Jumir Afart',
      'armony',
    ].filter(x => regex.test(x));
    
    console.log(filtered);