-1

I made a simple sort function but it still returns the original list for some reason.

function sortByPopular (item) {
    let items_sold = item.slice();

    items_sold.sort(function(a,b) {
        return a.quantity_sold > b.quantity_sold;
    });
 
    loadPopularItems("popular-items", items_sold); //this sends it to the html
}

kai-san
  • 33
  • 3
  • 4
    You need to return a number, not a boolean. Return a positive number to put `b` first, negative to put `a` first, 0 to keep them the same – Nicholas Tower Apr 13 '21 at 14:40
  • I'm guessing `item` is the array you wish to sort? Do all of the objects in the `item` array have the `quantity_sold ` property? – 90909090 Apr 13 '21 at 14:43
  • 1
    See the 2nd answer in [Array.sort() doesn't sort numbers correctly](https://stackoverflow.com/questions/7000851/array-sort-doesnt-sort-numbers-correctly). Just change the `>` symbol to a `-` symbol. `return a.quantity_sold - b.quantity_sold;` – Igor Apr 13 '21 at 14:43
  • Please read documentation on the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), it even has examples for simple number sorting. Note, that `(a, b) => a > b` is an invalid comparefn, and while engines don't typically play evil, the result of sorting with it as argument is specification wise implementation dependent, and arbitrary. – ASDFGerte Apr 13 '21 at 14:45
  • 1
    thanks everyone, I thought I searched enough and just couldn't find an answer but I was wrong – kai-san Apr 13 '21 at 14:48

1 Answers1

1

The callback function needs to return a number distinguishing between three states, not a boolean:

  • If the two elements should sort equal, return 0
  • If a should sort before b, return any number less than 0
  • If a should sort after b, return any number greater than 0

If the quantity_sold property is a number, you can do this simply: return a.quantity_sold - b.quantity_sold;

If it's not a number, you need appropriate if statements:

if ( a.quantity_sold > b.quantity_sold ) {
    return -1;
}
elseif ( a.quantity_sold < b.quantity_sold ) {
    return 1;
}
else {
    return 0;
}
IMSoP
  • 89,526
  • 13
  • 117
  • 169