Search code examples
javascriptarraysreactjsarray-filter

react filter first three of every type


I am making a react project and at one point, I have an API which returns the following:

APIresult = [
    {
        category: "first",
        value: "honey"
    },
    {
        category: "first",
        value: "milk"
    },
    {
        category: "first",
        value: "biscuit"
    },
    {
        category: "first",
        value: "tea"
    },
    {
        category: "first",
        value: "coffee"
    },
    {
        category: "second",
        value: "pillow"
    },
    {
        category: "second",
        value: "bedsheet"
    },
    {
        category: "second",
        value: "tv"
    },
    {
        category: "second",
        value: "fridge"
    },
    {
        category: "second",
        value: "airconditioner"
    },

]

I want to filter this array so that I get the first three of every category. ie, the result that I am expecting is

APIresult = [
    {
        category: "first",
        value: "honey"
    },
    {
        category: "first",
        value: "milk"
    },
    {
        category: "first",
        value: "biscuit"
    },
    {
        category: "second",
        value: "pillow"
    },
    {
        category: "second",
        value: "bedsheet"
    },
    {
        category: "second",
        value: "tv"
    }

]

I know I have to do APIresults.filter over it but how do I limit the result to just the first 3 of every type?


Solution

  • You can make use of Array.prototype.reduce to filter and froup your array so that the first three elements of each category are available and then join the results within an array again

    const APIresult = [
        {
            category: "first",
            value: "honey"
        },
        {
            category: "first",
            value: "milk"
        },
        {
            category: "first",
            value: "biscuit"
        },
        {
            category: "first",
            value: "tea"
        },
        {
            category: "first",
            value: "coffee"
        },
        {
            category: "second",
            value: "pillow"
        },
        {
            category: "second",
            value: "bedsheet"
        },
        {
            category: "second",
            value: "tv"
        },
        {
            category: "second",
            value: "fridge"
        },
        {
            category: "second",
            value: "airconditioner"
        },
    
    ]
    
    const res = [].concat(...Object.values(APIresult.reduce((acc, item) => {
       if(acc[item.category] && acc[item.category].length < 3) {
          acc[item.category].push(item);
       } else if(!acc[item.category]) {
           acc[item.category] = [item];
       }
       return acc;
    }, {})))
    console.log(res);