Search code examples
arraystypescriptarray-maparray-filter

Nested filter in typescript


I have a JSON array, which looks as follows.

[
  {
        id: 1,
        name: 'Alex',
        activity: [
           {
                id: 'A1',
                status: true
            },

            {
                id: 'A2',
                status: true
            },

            {
                id: 'A3',
                status: false
            }

        ]
    },
    {
        id: 2,
        name: 'John',
        activity: [
            {
                id: 'A6',
                status: true
            },

            {
                id: 'A8',
                status: false
            },

            {
                id: 'A7',
                status: false
            }

        ]
    }
]

I want to get an array of activity id whose status should be true.I can achieve this with nester for or forEach loop. But here I am looking to achieve with the help of array functions like filter, map, and some.

I have already tried with the following.

let newArr=arr.filter(a=> a.activity.filter(b=> b.status).map(c=> c.id))

But I didn't get the correct answer Expected output

['A1','A2','A6']


Solution

  • function filter_activity(activities) {
        return activities
            && activities.length
            && activities.map(x => x.activity)
                .flat().filter(activity => activity.status)
                .map(x => x.id) || [];
    }
    

    Illustration

    function filter_activity(activities) {
      return activities &&
        activities.length &&
        activities.map(x => x.activity)
        .flat().filter(activity => activity.status)
        .map(x => x.id) || [];
    }
    const input = [{
        id: 1,
        name: 'Alex',
        activity: [{
            id: 'A1',
            status: true
          },
          {
            id: 'A2',
            status: true
          },
          {
            id: 'A3',
            status: false
          }
        ]
      },
      {
        id: 2,
        name: 'John',
        activity: [{
            id: 'A6',
            status: true
          },
          {
            id: 'A8',
            status: false
          },
          {
            id: 'A7',
            status: false
          }
        ]
      }
    ];
    console.log(filter_activity(input));


    WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET