0

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 tallys, we'd get 9, 11, and 2 respectively, in which case I would like something like this:

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.

3 Answers 3

2

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

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)

Sign up to request clarification or add additional context in comments.

Comments

0

You can do this with 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);

Comments

0

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. You can use .reduce() to calculate the sum. Here the acc is an accumulated value which starts off as 0 and gets added to every time the reduce callback is called.

Once you have the sums for each object you can sort based on the sums of each object using .sort() like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.