-4

I have the following multidimensional array stored in a variable named posts

{ID: 141, categories: ["candy", "fruits", "vegetables"]}
{ID: 142, categories: ["fruits"]}
{ID: 143, categories: ["candy", "vegetables"]}

Is it possible to create a new array only with items containing candy in the categories?

So the new posts variable will have the following array:

{ID: 141, categories: ["candy", "fruits", "vegetables"]}
{ID: 143, categories: ["candy", "vegetables"]}
1
  • 3
    yes it is possible, what have you tried? Commented Mar 17, 2018 at 17:09

1 Answer 1

3

You can use filter() and includes() methods and return new array.

const data = [{ID: 141, categories: ["candy", "fruits", "vegetables"]}, {ID: 142, categories: ["fruits"]}, {ID: 131, categories: ["candy", "vegetables"]}]

const result = data.filter(({categories}) => categories.includes('candy'));
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.