【问题标题】:JavaScript Reduce Inside MapJavaScript 减少内部映射
【发布时间】:2020-06-20 11:14:03
【问题描述】:

我正在尝试根据对象属性之一的总和对对象数组进行排序。本质上是这样的:

array = [
          {
            id:4,
            tally: [1, 3, 5]
          },
         {
            id: 6,
            tally: [2, 3, 6]
         },
         {
            id: 9,
            tally: [2, 1, -1]
         }
]

如果我们将相应的tallys 相加,我们将分别得到 9、11 和 2,在这种情况下,我想要这样的结果:

array = [
          {
            id:6,
            tally: [2, 3, 6]
          },
         {
            id: 6,
            tally: [1, 3, 5]
         },
         {
            id: 9,
            tally: [2, 1, -1]
         }
]

我知道这是mapreduce 的某种组合,但我正在努力寻找如何以正确的 React 格式对其进行编码。

【问题讨论】:

    标签: javascript mapreduce


    【解决方案1】:

    您可以先使用 mapreduce 计算每个对象的总和,然后使用 sort 方法对新数组进行排序,然后使用另一个 map 方法删除 sum 属性

    const array = [{
        id: 4,
        tally: [1, 3, 5]
      },
      {
        id: 6,
        tally: [2, 3, 6]
      },
      {
        id: 9,
        tally: [2, 1, -1]
      }
    ]
    
    const sorted = array
      .map(({ tally, ...rest }) => ({
        sum: tally.reduce((r, e) => r + e, 0), tally, ...rest
      }))
      .sort((a, b) => b.sum - a.sum)
      .map(({ sum, ...rest }) => rest)
    
    console.log(sorted)

    【讨论】:

      【解决方案2】:

      您可以使用sort

      var arr=[{id:4,
                tally: [1, 3, 5]},
               {id: 6,
                tally: [2, 3, 6]},
               {id: 9,
                tally: [2, 1, -1]}
      ]
      
      var result =arr.sort((a,b)=>{
          aa = a.tally.reduce((acc,elem)=>acc+elem,0);
          bb = b.tally.reduce((acc,elem)=>acc+elem,0);
          return bb-aa;
      });
      
      console.log(result);

      【讨论】:

        【解决方案3】:

        您可以先将总和累加到Map,其中每个键是对象的id,每个值是该对象的tally 数组的总和。您可以使用.reduce() 来计算总和。这里的acc 是一个累积值,从 0 开始,每次调用 reduce 回调时都会添加。

        获得每个对象的总和后,您可以使用 .sort() 根据每个对象的总和进行排序,如下所示:

        const array = [{ id: 4, tally: [1, 3, 5] }, { id: 6, tally: [2, 3, 6] }, { id: 9, tally: [2, 1, -1] }];
        const sumMap = new Map(array.map(
          ({id, tally}) => [id, tally.reduce((acc, n) => acc+n, 0)])
        );
        const res = array.sort((a, b) => sumMap.get(b.id) - sumMap.get(a.id));
        
        console.log(res);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-21
          • 1970-01-01
          • 1970-01-01
          • 2021-02-05
          • 2016-03-04
          • 1970-01-01
          • 1970-01-01
          • 2020-07-27
          相关资源
          最近更新 更多