在Javascript中按日期分组 [英] group by Date in Javascript

查看:49
本文介绍了在Javascript中按日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多生日

const birthdays = [
    {name: 'John', birthday: '08-08-1960'},
    {name: 'James', birthday: '08-25-1960'},
    {name: 'Mary', birthday: '01-01-1990'},
]

,我需要生成一个新数组,其生日按 month-year

and I need to generate a new array with the birthdays grouped by month-year

const grouped = [
    {'08-1960': [
        {name: 'John', birthday: '08-08-1960'},
        {name: 'James', birthday: '08-25-1960'},        
    ]},
    {'01-1990': [
        {name: 'Mary', birthday: '01-01-1990'}, 
    ]},
]

我正在看这样的东西.使用 moment lodash

I was looking at something like this. using moment and lodash

let groupedResults = _.groupBy(results, (result) => moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek'));

但是我无法想象如何生成新的数组结构(以年月为键)谢谢.

but I can´t imagine how to generate the new array structure (with the month-year as keys) thank you.

更新:它应该返回一个数组,而不是一个对象:facepalm

update: it should return an array not an object :facepalm

推荐答案

您可以使用 reduce()

  • 在对象数组上应用 reduce()并将累加器设置为空对象 {}
  • 然后在-之前生日 split()生日,并只获取第一个和第三个元素.
  • 如果键存在,则是 concat()的新值的累加器.否则,将其 concat()设置为空数组 [] ,然后将其设置为累加器的属性.
  • Apply reduce() on array of object and set accumulator to empty object {}
  • Then split() birthday by - and get only get first and third element.
  • If the key exist is accumulator that concat() new value to it. Otherwise concat() it to empty array [] and then set it as property of accumulator.

const arr = [
    {name: 'John', birthday: '08-08-1960'},
    {name: 'James', birthday: '08-25-1960'},
    {name: 'John', birthday: '01-01-1990'},
]

let res = arr.reduce((ac,a) => {
 let key = a.birthday.split('-');
 key = `${key[0]}-${key[2]}`;
 ac[key] = (ac[key] || []).concat(a);
 return ac;
},{})
res = Object.entries(res).map(([k,v]) => ({[k]:v}))
console.log(res)

这篇关于在Javascript中按日期分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆