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

Efficient Logic to reduce time complexity(n^3) and get all variables

  • getrewarddata is object
  • d1,d2,d3... are variables

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

Answer

I think you search for a grouping method. And this one works fine: https://stackoverflow.com/a/34890276/11139208

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