'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}]


Solution 1:[1]

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)

Solution 2:[2]

The reason your code does not work is because you are not accessing the properties right and trying to match a whole object. x.includes('A') is doing a comparison with the whole object that is x.

If you just want to filter the objects in an array based on some specific property in them here's how you can do it.

Sample:

let data = [{id: 1, type: "Pizza"}, {id: 1, type: "Taco"}, {id: 1, type: "Pasta"}, {id: 1, type: "Sandwich"}, {id: 1, type: "Pumpkin Pie"}]

Process:

data.filter(x => x.type.toLowerCase().includes('pizza'))

Output:

[{id: 1, type: Pizza}]

or in your case if you want to just sort by the first letter, you can do:

data.filter(x => x.type.toLowerCase().startsWith('p'))

Returns: [ {id: 1, type: "Pizza"},{id: 1, type: "Pasta"}, {id: 1, type: "Pumpkin Pie"} ]`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 majid savalanpour
Solution 2