javascriptarraysnode.jssortingtimsort

Getting 'undefined' returned when trying to sort array of objects with TimSort


Here is a code snippet that is very close to what I'm trying to implement in my project: https://repl.it/@Twinbird24/TimSort-example

var timsort = require('timsort');

const arr = [
  {
    name: 'Amy',
    age: 23
  },
  {
    name: 'Bob',
    age: 34
  },
  {
    name: 'Cary',
    age: 18
  }
];

function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    return a.sortBy - b.sortBy;
  }
  return timsort.sort(objectsArr, stringCompare);
}

const sortedArr = sort(arr, 'name');

console.log(sortedArr);

Here is the package I'm using: https://www.npmjs.com/package/timsort

I'm trying to sort my array of objects by each object's name property, which holds a string—although my function can also be passed another item to sort by (i.e. 'age').

The documentation for TimSort is not very clear and looking through the source code I'm still not quite able to figure out how to configure my code.

You'll notice in my code that I would also like to choose to sort by 'ascending' or 'descending' but I'm not sure how to add that into the TimSort method I'm using.


Solution

  • Your string compare doesn't compare strings. It will only work for types like numbers or those that have a valueOf, like Date.

    Perhaps if you changed it to a < b ? -1 : a > b ? 1 : 0, it would work a little better. So how about this?:

    function sort(objectsArr, sortBy, sortOrder = 'ascending') {
      function stringCompare(a, b) {
        const left = a[sortBy], right = b[sortBy];
        return left < right ? -1 : left > right ? 1 : 0;
      }
      return timsort.sort(objectsArr, stringCompare);
    }
    

    This still doesn't answer you ascending/descending question. It should be straightforward from here, but please ask another question if you can't get it.