-3

Let's say I have an array of parent objects. Each parent has been given points and each parent has N children, each children has points as well. How can I sort the parents by total points descending (most points to least points). I've provided an example:

const parentsArray = [
{id:1, name: "Wendy", points:3, children: [{name: "Josh", points:2}, {name: "Josh", points: 15}]},
{id:2, name: "George", points: 10, children: [{name: "Mary", points:6}]},
{id:3, name: "Anne", points: 2, children: [{name: "Sarah", points:1.41},
{name: "Kim", points:0.41}]}
];

This is currently my code, but it only sorts on how to sort the points of the parent and does not take into account the points of the children:

parentsArray.sort((p1, p2) => (p2.points - p1.points));
TeetoGo
  • 1
  • 2

1 Answers1

0

You can make use of Array.sort:

const parentsArray = [
{id:1, name: "Wendy", points:3, children: [{name: "Josh", points:2}, {name: "Josh"}]},
{id:2, name: "George", points: 10, children: [{name: "Mary", points:6}]},
{id:3, name: "Anne", points: 2, children: [{name: "Sarah", points:1.41},
{name: "Kim", points:0.41}]}
];
parentsArray.sort((a, b)=>{
  return b.points - a.points;
})
parentsArray.forEach((e)=>{
  e.children.sort((a,b)=>{return b.points - a.points});
})
console.log(parentsArray);
Spectric
  • 30,714
  • 6
  • 20
  • 43