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}]
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}]
Share
Improve this question
edited Jun 6, 2020 at 23:46
Rachid O
14.1k16 gold badges70 silver badges94 bronze badges
asked Jun 6, 2020 at 20:20
Shalin PatelShalin Patel
1793 silver badges13 bronze badges
1
- 1 Hi, please format your code a bit better. :) – Danyal Commented Jun 6, 2020 at 20:36
2 Answers
Reset to default 4Try 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)
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 parison 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"} ]`