Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter inside filter in JavaScript

Tags:

javascript

I need to filter some data inside an array of objects which is contained in another array of objects. Here is the sample structure of my data. I need to filter on categories.

[
    {
    id: 540,
    name:'Makeup kit'
    slug:'makeup-kit',
    status:'publish',
    categories: [
            {
                id: 42, name:'Fashion',slug:'fashion'
            },
            {
                id: 43, name:'Beauty',slug:'beauty'
            }
        ]
    },
    {
    id: 541,
    name:'Silicon gloves'
    slug:'silicon-gloves',
    status:'publish',
    categories: [
            {
                id: 44, name:'Health',slug:'health'
            }
        ]
    },
    {
    id: 650,
    name:'Julep Mask'
    slug:'julep-mask',
    status:'publish',
    categories: [
            {
                id: 43, name:'Beauty',slug:'beauty'
            }
        ]
    }
]

Here is how I'm trying

beautyProducts=temp1.filter(product=>product.categories.filter(cat=>cat.id===43))

but my solution doesn't seem to work.

like image 958
Lint Avatar asked Oct 17 '25 17:10

Lint


1 Answers

Array#filter() expects the function you give it to return a truthy or falsy value. Elements for which the function returns a truthy value are kept in the new array, and those that give a falsy value are removed.

You want to keep only elements for which one of the categories has an id of 43. Using a second filter, then, makes no sense here: it returns an array, and arrays are always truthy; therefore the first filter will always receive an array for each element and all elements are kept in the new array.

Instead of a second filter, you should use Array#some() - you want to know if any of the categories have id===43, and if none of them do, then you want a falsy value so that the product gets excluded from the results.

Simple change:

beautyProducts = temp1.filter(product => product.categories.some(cat => cat.id === 43))

Here is a working sample:

let temp1 = [{id:540,name:'Makeup kit',slug:'makeup-kit',status:'publish',categories:[{id:42,name:'Fashion',slug:'fashion'},{id:43,name:'Beauty',slug:'beauty'}]},{id:541,name:'Silicon gloves',slug:'silicon-gloves',status:'publish',categories:[{id:44,name:'Health',slug:'health'}]},{id:650,name:'Julep Mask',slug:'julep-mask',status:'publish',categories:[{id:43,name:'Beauty',slug:'beauty'}]}];

let beautyProducts = temp1.filter(product => product.categories.some(cat => cat.id === 43));

console.log(beautyProducts);
like image 73
Klaycon Avatar answered Oct 20 '25 07:10

Klaycon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!