Home > Back-end >  Filtering an array of objects against items in second array
Filtering an array of objects against items in second array

Time:04-13

I'm trying to filter an array of objects to return only the objects that match items in a second array and I can't seem to get it to work.

export const Config = [
    {
        labels: ['label_1', 'label_2', 'label_3'],
        title: 'Home',
        link: '/',
    },
    {
        labels: ['label_1'],
        title: 'One',
        link: '/one/',
    },
    {
        labels: ['label_2'],
        title: 'Two',
        link: '/two/',
    },
    {
        labels: ['label_3'],
        title: 'Three',
        link: '/Three/',
    },
]

const filters = [
    "label_1",
    "label_2"
]

const filterdLabels = config.filter(item => {
  return filters.forEach(filter => {
    return item.labels.includes(filter)
  }) 
})

This is my code, I would expect that filtered labels is an array of any objects that have the matching labels in the labels array.

Any ideas?

Thanks

CodePudding user response:

const config = [{labels: ['label_1', 'label_2', 'label_3'],title: 'Home',link: '/'},{labels: ['label_1'],title: 'One',link: '/one/'},{labels: ['label_2'],title: 'Two',link: '/two/'}, {labels: ['label_3'],title: 'Three',link: '/Three/'}];

const filters = ["label_1","label_2"];

const output = config.filter(
   ({labels}) => labels.some(label => filters.includes(label))
)
//If, and only if you want to remove labels that do not match!!!!
.map(
    ({labels,...rest}) => 
    ({labels:labels.filter(label => filters.includes(label)),...rest})
);

console.log( output );

CodePudding user response:

const filterdLabels = config.filter(item => filters.includes(item.lables.toString()))

CodePudding user response:

.forEach(...) is not going to return anything, just undefined, that is a falsy value, so your filter will return empty.

I am guessing that what you want is as in the following:

const config = [
    {
        labels: ['label_1', 'label_2', 'label_3'],
        title: 'Home',
        link: '/',
    },
    {
        labels: ['label_1'],
        title: 'One',
        link: '/one/',
    },
    {
        labels: ['label_2'],
        title: 'Two',
        link: '/two/',
    },
    {
        labels: ['label_3'],
        title: 'Three',
        link: '/Three/',
    },
]

const filters = [
    "label_1",
    "label_2"
]

const filteredLabels = config.filter(item => {
  return filters.every(label => {
    return item.labels.includes(label)
  }) 
})

Then your result will match the first item in your config, i.e. {labels: ['label_1', 'label_2', 'label_3'], title: 'Home', link: '/'}, which is the only one that has both 'label_1' and 'label_2'. The result of the filter is an array with only that element.
Change every to some to accept any element with either 'label_1' or 'label_2' and not necessarily both (1st to 3rd elements will match in this case).

  • Related