Need help with lodash method: sortBy()

I am trying to sort some data that looks like this:

I want the data to be sorted by the date value (2nd element of array) and decided to use lodash sortBy() method. But no matter what I did/do, nothing is changing.

First I tried sorting on date, to no avail. So I thought maybe the fact that it was showing as a string (in dataset) was a problem. So I tried to aim smaller and sort by the first value, a number. After several trials, this is the code that I am now trying to debug, in the hopes that I can at least understand what I am doing wrong (as opposed to actually reaching a point that solves my initial problem!):

countHH(){
//some other code that creates the hhPerDay dataset

console.log("hhPerDay before: ");
    console.log(hhPerDay);
    _.sortBy(hhPerDay, [
      function(hhPerDay) {
        for (let i = 0; i < hhPerDay.length; i++) {
          console.log(hhPerDay[i][0]);
          return hhPerDay[i][0];
        }
      }
    ]);
    console.log("hhPerDay after: ");
    console.log(hhPerDay);
    return hhPerDay;

}

Can someone please take a look and let me know if I am using sortBy() correctly or not?

Also, this line: console.log(hhPerDay[i][0]) returns undefined so I know that code is already broken by this point.

Thank you.

You can use native javascript to sort by any element in a multidimensional array such as you have, you don’t need lodash

example say your array is

const arr = [['x', 5], ['y',10], ['z', 2]]

and you want to sort by the second element ascending

arr.sort((a, b) => a[1] - b[1])

console.log(arr)

// [ [ 'z', 2 ], [ 'x', 5 ], [ 'y', 10 ] ]

the trick is in understanding the how the native JavaScript sort callback acts on the compareFunction,

For sorting dates you may want to convert the date/time to a unix stamp to use in the compareFunction for precision.

2 Likes

Thanks @Dereje1…I’ll definitely revert back to vanilla JS if lodash doesn’t work. Was hoping to avoid it but that might not be possible.

if hhPerDay is a 2D array as shown in your screenshot, then the problem is probably that you are iterating in your function. (Also, note that even if you needed to iterate on a further nested array, you are returning on the first element, so your for loop wouldn’t be doing you much.

var hhPerDay = [
  [346, '2016-07-01'],
  [392, '2016-07-02'],
  [417, '2016-07-03'],
  [46, '2016-07-04']
];
 
_.sortBy(hhPerDay, [function(each) { return each[0]; }]);
// returns [[46, "2016-07-04"], [346, "2016-07-01"], [392, "2016-07-02"], [417, "2016-07-03"]]
 
_.sortBy(hhPerDay, [function(each) { return each[1]; }]);
// returns [[346, "2016-07-01"], [392, "2016-07-02"], [417, "2016-07-03"], [46, "2016-07-04"]]
1 Like

Thanks guys and gals. Y’all are the best, as usual.