【问题标题】:Building an Object of arrays comparing two arrays using reduce使用reduce构建比较两个数组的数组对象
【发布时间】:2022-09-23 04:11:25
【问题描述】:

我正在尝试填充图表,并且数据必须以特定方式格式化。我终于把数据变成了正确的形状,但我意识到我缺少值。

所以我有一个日期数组:

const labels = [\"Sep.08\", \"Sep.09\", \"Sep.12\", \"Sep.13\", \"Sep.14\"]

我有一个包含namedate以及count的对象数组:

const Data = [
{date: \"Sep.08\", name: \"User1\", count: 8},
{date: \"Sep.08\", name: \"User2\", count: 2},
{date: \"Sep.09\", name: \"User2\", count: 3},
{date: \"Sep.09\", name: \"User3\", count: 1},
{date: \"Sep.12\", name: \"User1\", count: 11},
{date: \"Sep.13\", name: \"User1\", count: 3},
{date: \"Sep.13\", name: \"User2\", count: 3},
{date: \"Sep.14\", name: \"User2\", count: 7},
]

我要完成的工作:

  1. 每个名称都应该在新对象中有一个数组
  2. 每个日期都应该在数组中表示,以便每个数组 是相同的长度。如果用户没有代表其中之一的对象 标签数组中的日期,则应在新数组中的该索引处添加零。

    我的预期结果是:

    const result = {
    User1: [8,0,11,3,0], //0\'s where user has no object with the dates of \"Sep.09\" & \"Sep.14\"
    User2: [2,3,0,3,7],
    User3: [0,1,0,0,0],
    }
    

    我正在使用.reduce 创建我的新对象:

    const Data = [
    {date: \"Sep.08\", name: \"User1\", count: 8},
    {date: \"Sep.08\", name: \"User2\", count: 2},
    {date: \"Sep.09\", name: \"User2\", count: 3},
    {date: \"Sep.09\", name: \"User3\", count: 1},
    {date: \"Sep.12\", name: \"User1\", count: 11},
    {date: \"Sep.13\", name: \"User1\", count: 3},
    {date: \"Sep.13\", name: \"User2\", count: 3},
    {date: \"Sep.14\", name: \"User2\", count: 7},
    ]
    
    const labels = [\"Sep.08\", \"Sep.09\", \"Sep.12\", \"Sep.13\",\"Sep.14\"]
    
    
    const groups = Data.reduce((acc, obj) => {
     
      if (!acc[obj.name]) {
        acc[obj.name] = [];
      }
     
      acc[obj.name].push(obj.count);
    
      return acc;
    }, {});
    
    console.log(groups)

    问题是我不确定如何将标签与 acc 对象中的名称进行比较。 Reduce 对我来说非常令人困惑,但它似乎是按照我的需要格式化数据的最干净的方法。任何意见将是有益的。

    标签: javascript arrays object reduce


    【解决方案1】:

    你可以这样做:

    const Data = [{date:"Sep.08",name:"User1",count:8},{date:"Sep.08",name:"User2",count:2},{date:"Sep.09",name:"User2",count:3},{date:"Sep.09",name:"User3",count:1},{date:"Sep.12",name:"User1",count:11},{date:"Sep.13",name:"User1",count:3},{date:"Sep.13",name:"User2",count:3},{date:"Sep.14",name:"User2",count:7},];
    const labels = ["Sep.08","Sep.09","Sep.12","Sep.13","Sep.14"];
    
    const groups = Data.reduce((acc, { date, name, count }) => {
      if (!acc[name]) {
        // Fill an array with zeroes, the length of labels
        acc[name] = labels.map(_ => 0);
      }
      // Find the index of the current label
      const labelIndex = labels.indexOf(date);
      // Replace the corresponding zero
      acc[name][labelIndex] = count;
      
      return acc;
    }, {});
    
    
    console.log(groups);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多