I have the following array containing a JSON object defined below
[
{
"modDate": "2017-06-20"
},
{
"modDate": "2017-10-24"
},
{
"modDate": "2017-08-03"
}
]
and i want the result to be grouped in first place by month and then sorted by in descending order by month.
I have tried grouping it with this
grouped_items = _.groupBy(data, (b) ->
moment(b.modDate).startOf('month').format('YYYY/MM')
but is am not getting the correct result.
I have the following array containing a JSON object defined below
[
{
"modDate": "2017-06-20"
},
{
"modDate": "2017-10-24"
},
{
"modDate": "2017-08-03"
}
]
and i want the result to be grouped in first place by month and then sorted by in descending order by month.
I have tried grouping it with this
grouped_items = _.groupBy(data, (b) ->
moment(b.modDate).startOf('month').format('YYYY/MM')
but is am not getting the correct result.
Share Improve this question edited Apr 26, 2018 at 14:05 croppio. asked Apr 26, 2018 at 13:50 croppio.croppio. 1,8835 gold badges28 silver badges45 bronze badges 1- just a typo, fixed – croppio. Commented Apr 26, 2018 at 14:05
1 Answer
Reset to default 8If I understood you correctly, you want to create a grouped collection of the data by the month, and then sort the values descendingly by the day of month (as sorting by month in the values doesn't make sense).
If so, the following should work:
const data = [{"modDate":"2017-06-20"},{"modDate":"2017-06-25"},{"modDate":"2017-10-24"},{"modDate":"2017-10-20"},{"modDate":"2017-08-03"}];
let grouped_items = _.groupBy(data, (b) =>
moment(b.modDate).startOf('month').format('YYYY/MM'));
_.values(grouped_items)
.forEach(arr => arr.sort((a, b) => moment(a.modDate).day() - moment(b.modDate).day()));
console.log(grouped_items);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.22.1/moment.min.js"></script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744207768a4563187.html
评论列表(0条)