Home > Mobile >  Filter array based on category of elements
Filter array based on category of elements

Time:02-01

I want to filter an array based on the category of its objects. So for example,

Take this array:

const base = [
0: {id: 1, category: 'earth'},
1: {id: 2, category: 'moon'},
2: {id: 3, category: 'earth'},
]

And return a filtered array with only the category 'earth'.

const filtered = [
0: {id: 1, category: 'earth'},
1: {id: 3, category: 'earth'},
]

I have tried using .filter() to no avail...

CodePudding user response:

You can try this code:

const categories = [
  {id: 1, category: 'earth'},
  {id: 2, category: 'moon'},
  {id: 3, category: 'earth'},
];
const result = categories.filter(({ category  }) => category === "earth");
  • Related