skip to Main Content

I have an array of objects like this:

[
  {
    category: 'ELECTRONICS',
    sub_category: 'CONSOLE'
  },
  {
    category: 'ELECTRONICS',
    sub_category: 'CONSOLE'
  },
  {
    category: 'ELECTRONICS',
    sub_category: 'TV'
  }
]

Now I want to filter when category and sub_category same.

How can I do it ?

2

Answers


  1. A simple comparison of the two string will do the trick.

    const data = [
      {
        category: "ELECTRONICS",
        sub_category: "CONSOLE"
      },
      {
        category: "ELECTRONICS",
        sub_category: "CONSOLE"
      },
      {
        category: "ELECTRONICS",
        sub_category: "TV"
      }
    ];
    
    const result = data.filter(e => e.category === e.sub_category);
    console.log(result);
    Login or Signup to reply.
  2. const data = [
      {
        category: 'ELECTRONICS',
        sub_category: 'CONSOLE'
      },
      {
        category: 'ELECTRONICS',
        sub_category: 'CONSOLE'
      },
      {
        category: 'ELECTRONICS',
        sub_category: 'TV'
      }
    ]
    
    const filter = data.filter(i => i.category == "ELECTRONICS" && i.sub_category == "TV")
    
    console.log(filter)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search