skip to Main Content
let users = [
  {
    "id": 1,
    "name": "Ricardo",
    "serail_no": 463494,
    "occupation": "IT Specialist"
  },
  {
    "id": 2,
    "name": "Saptak",
    "serail_no": 749694,
    "occupation": "Teacher"
  },
  {
    "id": 3,
    "name": "Antonio",
    "serail_no": 406406,
    "occupation": "IT Specialist"
  },
  {
    "id": 4,
    "name": "Dimitri",
    "serail_no": 2503853,
    "occupation": "Doctor"
  }
]

From the above Array List, I want to display only the objects which has same occupation in it.
So from the above list, if I take occupation = IT Specialist, then I ony want to display

[{
    "id": 1,
    "name": "Ricardo",
    "serail_no": 463494,
    "occupation": "IT Specialist"
  },{
    "id": 3,
    "name": "Antonio",
    "serail_no": 406406,
    "occupation": "IT Specialist"
  }]

I tried it using filter method, but wasn’t able to achieve it.
Will be very much grateful, if anyone helps me out in it with explanation.

2

Answers


  1. this should work 🙂

    const filtered_users = users.filter(
      (user) => user.occupation === "IT Specialist",
    );
    
    Login or Signup to reply.
  2. Here is how you would use filter:

    const users = [
      {
        "id": 1,
        "name": "Ricardo",
        "serail_no": 463494,
        "occupation": "IT Specialist"
      },
      {
        "id": 2,
        "name": "Saptak",
        "serail_no": 749694,
        "occupation": "Teacher"
      },
      {
        "id": 3,
        "name": "Antonio",
        "serail_no": 406406,
        "occupation": "IT Specialist"
      },
      {
        "id": 4,
        "name": "Dimitri",
        "serail_no": 2503853,
        "occupation": "Doctor"
      }
    ]
    
    const ocupation = 'IT Specialist';
    
    const filtered_users = users.filter((user) => user.occupation === ocupation);
    
    console.log(filtered_users);
    
    // output
    [
      {
        id: 1,
        name: 'Ricardo',
        serail_no: 463494,
        occupation: 'IT Specialist'
      },
      {
        id: 3,
        name: 'Antonio',
        serail_no: 406406,
        occupation: 'IT Specialist'
      }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search