Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an array of objects by their first letter in react/javascript

I am fairly new to React and javascript environment so some of the syntax and errors don't make sense to me. I have tried using the filter function something like this but gives me an error of undefined is not an object.

const temp = example.filter(x => x.includes('A'))

Example:

data = [{id: 1, type: Pizza}, {id: 2, type: Taco}, {id: 3, type: Pasta}, {id: 4, type: Sandwich}, {id: 5, type: Pumpkin Pie}]

Output:

temp = [{id: 1, type: Pizza}, {id: 3, type: Pasta}, {id: 5, type: Pumpkin Pie}]
like image 903
Shalin Patel Avatar asked Mar 31 '26 03:03

Shalin Patel


1 Answers

Try to use startWith:

let data = [{id: 1, type: 'Pizza'}, {id: 2, type: 'Taco'}, {id: 3, type: 'Pasta'}, {id: 4, type: 'Sandwich'}, {id: 5, type: 'Pumpkin Pie'}]

// Output:

let result = data.filter(f => f.type.toLowerCase().startsWith('p'))
console.log(result)
like image 84
StepUp Avatar answered Apr 02 '26 18:04

StepUp