0

I have the following array of objects

       var unsorted = [
                    {id:1, score_on_kilo:15},
                    {id:2, score_on_kilo:18},
                    {id:3, score_on_kilo:3},
                    {id:4, score_on_kilo:100},
                ];

         var sorted = unsorted.sort(function (a, b) {
                    return parseInt(a.score_on_kilo) > parseInt(b.score_on_kilo);
                });

When i check on the console.log(sorted) an getting

[
 {id:1, score_on_kilo:15},
 {id:2, score_on_kilo:18},
 {id:3, score_on_kilo:3},
 {id:4, score_on_kilo:100},
]

What am i missing out as also on the sorted even changing to return parseInt(a.score_on_kilo) - parseInt(b.score_on_kilo); still doesnt sort the arrays

I expected this to have

[
 {id:4, score_on_kilo:100},
 {id:2, score_on_kilo:18},
 {id:1, score_on_kilo:15},
 {id:3, score_on_kilo:3},
]

What am i missing?

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 4
    The `.sort()` callback function is supposed to return a *number*, not a boolean. In this case `a.score_on_kilo - b.score_on_kilo` would do it. – Pointy Oct 24 '19 at 14:42
  • 3
    Using `parseInt(a.score_on_kilo) - parseInt(b.score_on_kilo)`, your code works perfectly fine for me and sorts from ID 3, 1, 2, then 4. It's important to use this form and not the `>` form, as the sort function need to return 0 only if the elements are equal, while yours will return false (coerced to 0) if A is less than B. – IceMetalPunk Oct 24 '19 at 14:42
  • 1
    @IceMetalPunk true but it looks like the `parseInt()` is superfluous. – Pointy Oct 24 '19 at 14:43
  • Otherway round if you want the biggest at the top, `b - a` not `a - b` – George Oct 24 '19 at 14:43
  • @Pointy It is definitely superfluous, but also won't matter or break this code, so it's irrelevant to the question. – IceMetalPunk Oct 24 '19 at 14:44

1 Answers1

3

As a comment there suggested this would be what you want

unsorted.sort(function(a, b) {
  return parseInt(b.score_on_kilo) - parseInt(a.score_on_kilo);
});

Since you are supposed to return a number

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30