Home > Software engineering >  Filter inside a array of dicts by key
Filter inside a array of dicts by key

Time:02-15

I have that array of dict:

       arrayDict: [
        {
          Description: "Dict 0"
          Category: [
            'First',
            'Both',
          ],
        },
        {
          Description: "Dict 1",
          Category: [
            'Second',
            'Both',
          ],
        },
      ]

i would like to filter inside that array by Category. i will recieve a category and i need to filter. If i recieve "Both", i need to return "Dict 1" and "Dict 0". if i receive "Second", i return only "Dict 1".

How can i do that?

CodePudding user response:

You can achieve your goal by using filter method, like this:

const  arrayDict = [
        {
          Description: "Dict 0",
          Category: [
            'First',
            'Both',
          ],
        },
        {
          Description: "Dict 1",
          Category: [
            'Second',
            'Both',
          ],
        },
      ];
      
const filterDict = (key)=> arrayDict.filter(({Category}) => Category.includes(key))

console.log('First:',filterDict('First'));
console.log('Second:',filterDict('Second'));
console.log('Both:',filterDict('Both'));

CodePudding user response:

you can simply use the filter() : higher order function provided by JS.

var arrayDict = [
    {
      Description: "Dict 0",
      Category : [
        'First',
        'Both',
      ]
    },
    {
      Description: "Dict 1",
      Category : [
        'Second',
        'Both',
      ],
    },
  ]

  let input = 'Both';
  let filteredData = arrayDict.filter((elm) => {
    return elm.Category.includes(input)
})

console.log(filteredData);

CodePudding user response:

somthing like this:

arrayDict.filter((item)=> item.Category.includes('Both'))

CodePudding user response:

This is one possible implementation to achieve the desired result (using Array.reduce):

const arrayDict = [{
    Description: "Dict 0",
    Category: [
      'First',
      'Both',
    ]
  },
  {
    Description: "Dict 1",
    Category: [
      'Second',
      'Both',
    ]
  }
];

const filterArr = (category = 'Both', arr = arrayDict) => arr.reduce(
  (fin, itm) => (
    itm.Category.includes(category) ? `${fin}, ${itm.Description}` : fin
  ),
  ''
).slice(2).replace(',', ' and');

console.log(filterArr());
console.log(filterArr('First'));
console.log(filterArr('Second'));

  • Related