Lodash Add Keys To CountBy Function
I have a datasource as follows [ { 'physicalId': 2110, 'closedDate': '2017-06-25T00:00:00.000Z', 'allDay': true }, { 'physicalId': 2111, 'closedDate': '20
Solution 1:
You can use _.map
after _.countBy
:
_.map(_.countBy(source, "closedDate"), (val, key) => ({ date: key, total: val }))
Solution 2:
I am not sure but i think this mapkey function would help
Solution 3:
Using plain js, the following two reduce() would convert the original data to the desired format:
let d = [{
"physicalId": 2110,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 2111,
"closedDate": "2017-06-24T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 2111,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 4299,
"closedDate": "2017-06-24T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 4299,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
}
];
let r = [
...d.reduce((a, b) => {
a.set(b.closedDate, a.has(b.closedDate) ? a.get(b.closedDate) + 1 : 1);
return a;
}, new Map)
].reduce((a, b) => {
let [date, total] = [...b];
return a.concat({date, total});
}, []);
console.log(r);
Solution 4:
We are using here ES6 syntax, with .reduce()
and .find()
array helpers.
We are also using ES6 spread operator to change existing data inside our objects.
Here is working example.
var data = [
{
"physicalId": 2110,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 2111,
"closedDate": "2017-06-24T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 2111,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 4299,
"closedDate": "2017-06-24T00:00:00.000Z",
"allDay": true
},
{
"physicalId": 4299,
"closedDate": "2017-06-25T00:00:00.000Z",
"allDay": true
}
]
const newData = data.reduce((previous, current) => {
const recordExists = previous.find(record => record.date === current.closedDate);
if (!recordExists) {
return previous = [ ...previous, { date: current.closedDate, total: 1 } ];
}
recordExists.total += 1;
return [ ...previous, recordExists ];
}, []);
console.log(newData);
Post a Comment for "Lodash Add Keys To CountBy Function"