如何将多个过滤器组合成一个过滤器函数并获取特定月份的值?

How to combine multiple filter to a single filter function and get value for particular month?

减少时间复杂度(n^3)并获取所有变量的高效逻辑

//Object has multiple rewards and different month
const getrewarddata = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

//break array in particular month variable
let d3 = getrewarddata.filter((data) => data.month === 3);

let d2 = getrewarddata.filter((data) => data.month === 2);

let d1 = getrewarddata.filter((data) => data.month === 1);

console.log(d2);
console.log(d3);

使这更容易的唯一合理方法是创建一个 helper/wrapper 函数来跳过代码重复。

const wrapper = (month) => getrewarddata.filter((data) => data.month === month);

然后就用这个helper/wrapper:

let d3 = wrapper(3);
let d2 = wrapper(2);
let d1 = wrapper(1);

您的代码似乎有效。不确定你想要实现什么。您可以创建一个函数来为每个变量调用,以减少代码量。

const getrewarddata = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

function filter(arr, n){
    return arr.filter((data) => data.month === n)
}

let d1 = filter(getrewarddata, 1)
let d3 = filter(getrewarddata, 3)
console.log(d1)
console.log(d3)

我想你是在寻找一种分组方法。这个工作正常:

//Object has multiple rewards and different month
const getrewarddata = [{
        month: 6,
        year: 2021,
        reward: 6,
    },
    {
        month: 1,
        year: 2021,
        reward: 6,
    },
    {
        month: 3,
        year: 2021,
        reward: 6,
    },
];

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};


var groupedByMonth = groupBy(getrewarddata, "month");

console.log(groupedByMonth);

这是另一个你只需要遍历数组一次的地方。

let result = getrewarddata.reduce((acc, entry) => {
        if (acc[entry.month] == undefined) { 
            acc[entry.month] = [entry];
        } else {
            acc[entry.month].push(month)
        }
        return acc
    }, {})

这样你得到一个像这样的对象:

{
    "1": [
        {
            "month": 1,
            "year": 2021,
            "reward": 6
        }
    ],
    "3": [
        {
            "month": 3,
            "year": 2021,
            "reward": 6
        }
    ],
    "6": [
        {
            "month": 6,
            "year": 2021,
            "reward": 6
        }
    ]
}

你可以像普通对象一样查询

result[1]
=> [{
        "month": 1,
        "year": 2021,
        "reward": 6
    }]