JavaScript 缩小内部地图

JavaScript Reduce Inside Map

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

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

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

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

我知道它是 mapreduce 的某种组合,但我正在努力了解如何以合适的 React 格式对其进行编码。

您可以使用 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);

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

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)

您可以先将总和累加到 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);