简体   繁体   English

JavaScript 缩小内 Map

[英]JavaScript Reduce Inside Map

I am trying to sort an array of objects based on the sum of one of the object's property.我正在尝试根据对象属性之一的总和对对象数组进行排序。 Essentially, like this:本质上,像这样:

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

If we sum the corresponding tally s, we'd get 9, 11, and 2 respectively, in which case I would like something like this:如果我们将相应的tally s 相加,我们将分别得到 9、11 和 2,在这种情况下,我想要这样的东西:

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

I know it's some combination of map , reduce but I'm struggling to see how to code it up in the nice proper React format.我知道这是map的某种组合, reduce但我正在努力了解如何以正确的 React 格式对其进行编码。

You could first calculate sum in every object using map and reduce then sort that new array using sort method and then just remove sum property with another map method您可以首先使用map计算每个reduce中的总和,然后使用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)

You can do this with sort :你可以用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);

You can fist accumulate the sums into a Map , where each key is the id of an object and each value is the sum of that object's tally array.您可以先将总和累加到Map中,其中每个键是 object 的id ,每个值是该对象的tally数组的总和。 You can use .reduce() to calculate the sum.您可以使用.reduce()来计算总和。 Here the acc is an accumulated value which starts off as 0 and gets added to every time the reduce callback is called.这里的acc是一个累积值,从 0 开始,每次调用 reduce 回调时都会被添加。

Once you have the sums for each object you can sort based on the sums of each object using .sort() like so:获得每个 object 的总和后,您可以使用.sort()根据每个 object 的总和进行排序,如下所示:

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM