Array.sort

  var sortedInventors = inventors.sort(function (a, b) {
      var property = 'year';
       if (a[property] < b[property]) {
           return -1;
       }
       if (a[property] > b[property]) {
         return 1;
       }
       // a must be equal to b
       return 0;
     });

refactored es6 style:

     const sortedInventors = inventors.sort((a, b) => {
       const property = 'year';
        if (a[property] < b[property]) {
            return -1;
        }
        if (a[property] > b[property]) {
          return 1;
        }
        // a must be equal to b
        return 0;
      });

I would avoid Wes Bos minimized solution below as it doesn’t return 0 on duplicates which result in unstable sorting when having duplicates in the array.

     const sortedInventors = inventors.sort((a, b) => a.year > b.year ? 1 : -1);

Add your comment