0

Suppose, I have an array.

const arr = [
      {
        category: 'Diner',
        item: [
          {name: 'Chicken Rice', price: 200},
          {name: 'Mutton Rice', price: 300},
        ],
      },
      {
        category: 'Breakfast',
        item: [
          {name: 'Tea Bisuit', price: 100},
          {name: 'Bread Butter', price: 300},
          {name: 'Green Tea', price: 80},
        ],
      },
    ];

How can I filter the array according to the item name? For example, how can I filter the array with the item name Green Tea?

Output must be like this:

arr = [
        {
          category: 'Breakfast',
          item: [
            {name: 'Green Tea', price: 80},
          ],
       },
     ];

1 Answer 1

2

You could map through arr, with each element, filter item to which match the term

After that, filter the arr again to reject the elements whose item is empty

const arr = [ { category: "Diner", item: [ { name: "Chicken Rice", price: 200 }, { name: "Mutton Rice", price: 300 }, ], }, { category: "Breakfast", item: [ { name: "Tea Bisuit", price: 100 }, { name: "Bread Butter", price: 300 }, { name: "Green Tea", price: 80 }, ], }, ]

const term = "Green Tea"

const res = arr
  .map((categoryAndItems) => ({
    category: categoryAndItems.category,
    item: categoryAndItems.item.filter((item) => item.name === term),
  }))
  .filter((categoryAndItems) => categoryAndItems.item.length > 0)

console.log(res)

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

2 Comments

Minor suggestion, do filter first and then map. You do not need to transform objects that will be filtered out
@Rajesh sure, thanks. could filter in one go, I just want to clarify steps 🤣

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.