0

I'm trying to understand the sort function. If I want to sort an array descending based on its values I do this :

    var items = [
      { name: 'Edward', value: 21 },
      { name: 'Sharpe', value: 37 },
      { name: 'And', value: 45 },
      { name: 'The', value: -12 },
      { name: 'Magnetic', value: 13 },
      { name: 'Zeros', value: 37 }
    ];

    // sort by value
    const b = items.sort(function (a, b) {
       return b.value -  a.value; 
    });
    
    console.log(b)

It works but I'm not sure how exactly , what does b.value represent ? and how does substracting those values sort the array.

I tried logging b.value but i got a list of numbers in an order that didnt make sense. Same with a.value.

Also tried looking up the documentation for this method but couldnt understand it. Could be language barrier or poorly explained.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • [Please RTM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) it is VERY clear – mplungjan Apr 30 '20 at 11:03
  • To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN): `function compareNumbers(a, b) { return a - b; }` – mplungjan Apr 30 '20 at 11:06
  • 1
    From the dupe: https://stackoverflow.com/a/60313794/295783 – mplungjan Apr 30 '20 at 11:07
  • 1
    thanks everyone I should have look at other SO questions before posting @mplungjan – Kevin.a Apr 30 '20 at 11:10

0 Answers0