0

With the following array of strings in javascript, is there a way to use the .filter to filter by the first word?

['Desk_One', 'Desk_Two', 'Desk_Three', 'Chair_One', 'Chair_Two']

For example to .filter(x = 'Desk_*')

 ['Desk_One', 'Desk_Two', 'Desk_Three']

Maybe this needs to be a regex

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

4

You can use startsWith() function like this:

let array = ['Desk_One', 'Desk_Two', 'Desk_Three', 'Chair_One', 'Chair_Two'];

let result = array.filter((item)=>item.startsWith(array[0].split('_')[0]));
console.log(result)
NeNaD
  • 18,172
  • 8
  • 47
  • 89