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
  • 484,719
  • 26
  • 302
  • 397
Marci
  • 47
  • 6

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 Milosavljevic
  • 2,050
  • 3
  • 25