-3

This is my array that I have to sort from highest average grade to lowest.

let students= [
         {name:"Petar", year:1, average:4.35},
         {name:"Ivana", year:1, average:3.88},
         {name:"Marko", year:2, average:2.27},
         {name:"Davor", year:2, average:4.15},
         {name:"Petra", year:3, average:3.99},
         {name:"Ivan", year:3, average:4.33},
         {name:"Goran", year:3, average:3.74}
     ];


students.sort(function(a,b){
         return a[1] - b[1];
     });
  • Those are not arrays but objects -> [Working with objects | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Andreas Apr 02 '19 at 11:08

1 Answers1

2

The parameters a and b in sort function are objects and not array. Use dot to access the property of objects and not brackets.

let students= [
    {name:"Petar", year:1, average:4.35},
    {name:"Ivana", year:1, average:3.88},
    {name:"Marko", year:2, average:2.27},
    {name:"Davor", year:2, average:4.15},
    {name:"Petra", year:3, average:3.99},
    {name:"Ivan", year:3, average:4.33},
    {name:"Goran", year:3, average:3.74}
];

const output = students.sort((a, b) => b.average - a.average);

console.log(output);
random
  • 7,756
  • 3
  • 19
  • 25
  • 3
    Note sort mutates original and returns original so `output === students` – charlietfl Apr 02 '19 at 11:12
  • 1
    `sort()` mutates the orginal array use `students.slice(0).sort(....).map(x => ({...x}))`. 1)`slice()` to prevent mutating of original array. 2)`map()` to remove references and create a real copy. – Maheer Ali Apr 02 '19 at 11:14
  • 1
    @MaheerAli It depends on the needs of the reader in question. You might not find it troubling that the array is mutated. Also *slice* has a default first argument of `0`. - *"If `begin` is undefined, `slice` begins from index `0`."* - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Parameters) – 3limin4t0r Apr 02 '19 at 11:19