反应每种类型的前三个过滤器

我正在做一个React项目,并且有一点,我有一个API,它返回以下内容:

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"
    },

]

我想过滤此数组,以便获得每个类别的前三个。 即,我期望的结果是

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"
    }

]

我知道我必须对其执行APIresults.filter,但是如何将结果限制为每种类型的前3个?

评论
  • xid
    xid 回复

    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);