Group by date and receive total records of each date and assemble another matrix

Asked

Viewed 65 times

0

[ 
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-04", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-05", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },
    { data: "23-06", xxx: "xxx, yyy: "yyy },

]

Hello, I need to take the above array of the total record of each date and create another array of objects containing its own name and total as new key values for example:

[{
        "a": "23-04",
        "b": 3
    }, {
        "a": "23-05",
        "b": 3
    },
    {
        "a": "23-06",
        "b": 5
    }
]

Can be with es6, map, reduce or even with lodash/undescore

I thank anyone who can chew this because I’m three days old and it doesn’t come out the way I need it

1 answer

2


Two examples that seem to work...

var origem = [
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-04", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-05", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
    { data: "23-06", xxx: "xxx", yyy: "yyy" },
];

var result1 = Object.entries(origem.reduce((acc, o) => (acc[o.data] = (acc[o.data] || 0) + 1, acc), {}))
    .map(([a, b]) => ({ a, b }));


let counts = {};
origem.forEach(el => counts[el.data] = (counts[el.data] || 0) + 1);
var result2 = Object.entries(counts).map(([a, b]) => ({ a, b }));

console.log(result1);
console.log(result2);

  • For you I’m sure it was only a few minutes on the keyboard to help a stranger, for me it was a relief that already suffered 3 days. Its code not only seems to work: it is perfect for my purpose and fell like a glove including solving the keys a and b with map.... My many thanks to you my dear!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.