I have the following array of objects in a Node.js script:
[ { start: '10-05-2018', assigned_agent: '1257434' }, { start: '10-05-2018', assigned_agent: '1257434' }, { start: '10-05-2018', assigned_agent: '1257434' }, { start: '10-06-2018', assigned_agent: '1257434' }, { start: '10-05-2018', assigned_agent: '1277852' }, { start: '10-05-2018', assigned_agent: '1277852' } ]
What I need is to have this grouped by the start and assigned_agent keys. I have tried filter
function examples but no luck. Not, there are other key/value pairs in the array but omitting them for the sake of clarity. Also, while this is a Node.js script I do have Lodash available if that helps.
Thank you.
Advertisement
Answer
If you are ok with using lodash, try groupBy
const data = [ { start: "10-05-2018", assigned_agent: "1257434" }, { start: "10-05-2018", assigned_agent: "1257434" }, { start: "10-05-2018", assigned_agent: "1257434" }, { start: "10-06-2018", assigned_agent: "1257434" }, { start: "10-05-2018", assigned_agent: "1277852" }, { start: "10-05-2018", assigned_agent: "1277852" }, ] const group_by_both = _.chain(data) .groupBy((el) => `${el.start} ${el.assigned_agent}`) .values() .value() console.log(group_by_both)
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>