为了账号安全,请及时绑定邮箱和手机立即绑定

使用 reduce 计算数据组内的数据组

使用 reduce 计算数据组内的数据组

有只小跳蛙 2021-06-16 19:19:13
正如标题所说,我正在尝试计算数据组中的数据组:我的逻辑是将所有数据分组为状态,然后将日期分组为年份。以便输出应如下所示:state,year,countmo,1910,2in,1910,1il,1910,3or,1910,4co,1910,2nd,1910,1...mo,1911,5in,1911,4il,1911,6or,1911,2co,1911,8我使用的 CSV 有更多需要的列,我只对列state和year. 我下面的代码不起作用,任何帮助都会很棒。const countStates = filteredData.reduce((m, d) => {    if(!m[d.year]){      m[d.year] = {...d, count: 1};      return m;    }    m[d.state];    m[d.year];    m[d.year].count += 1;    return m;},{});const countedStates = Object.keys(countStates).map((k) =>  {    const item  = countStates[k];    return {        state: item.state,        year: item.year,        count: item.count    }})编辑我正在使用的数据集示例:datetime,city,state,country,shape,duration (seconds),duration (hours/min),comments,date posted,latitude,longitude 10/10/1949 20:30,san marcos,tx,us,cylinder,2700,45 minutes,"This event took place in early fall around 1949-50. It occurred after a Boy Scout meeting in the Baptist Church. The Baptist Church sit",4/27/2004,29.8830556,-97.941111110/10/1949 21:00,lackland afb,tx,,light,7200,1-2 hrs,"1949 Lackland AFB&#44 TX.  Lights racing across the sky & making 90 degree turns on a dime.",12/16/2005,29.38421,-98.58108210/10/1955 17:00,chester (uk/england),,gb,circle,20,20 seconds,"Green/Orange circular disc over Chester&#44 England",1/21/2008,53.2,-2.91666710/10/1956 21:00,edna,tx,us,circle,20,1/2 hour,"My older brother and twin sister were leaving the only Edna theater at about 9 PM&#44...we had our bikes and I took a different route home",1/17/2004,28.9783333,-96.645833310/10/1960 20:00,kaneohe,hi,us,light,900,15 minutes,"AS a Marine 1st Lt. flying an FJ4B fighter/attack aircraft on a solo night exercise&#44 I was at 50&#44000&#39 in a "clean" aircraft (no ordinan",1/22/2004,21.4180556,-157.803611110/10/1961 19:00,bristol,tn,us,sphere,300,5 minutes,"My father is now 89 my brother 52 the girl with us now 51 myself 49 and the other fellow which worked with my father if he&#39s still livi",4/27/2007,36.5950000,-82.1888889
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

下面的代码获取带有年份的一组状态,并使用reduce我们获取按年份分组的每个状态的计数


var data = [

    { year: '1910', state: 'mo', country: 'us' },

    { year: '1910', state: 'in', country: 'us' },

    { year: '1910', state: 'il', country: 'us' },

    { year: '1910', state: 'mo', country: 'us' },

    { year: '1911', state: 'in', country: 'us' },

    { year: '1911', state: 'il', country: 'us' },

    { year: '1911', state: 'mo', country: 'us' },

    { year: '1911', state: 'in', country: 'us' }

];


var organizedData = data.reduce((acc, val, index) => {

  acc[val.state] = acc[val.state] || {};

  acc[val.state][val.year] = (+acc[val.state][val.year] || 0) + 1;

  return acc;

}, {});


console.log(organizedData);


查看完整回答
反对 回复 2021-06-18
  • 1 回答
  • 0 关注
  • 158 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信