2

I got the unique product grades and product last delivered plucked from the products object so I can put them into a dropdown as a filter using underscore. How can I sort the product grades and last delivered dates using underscore or angular before I put them into the drop down?

product_grades = ["", "40", "20", "30", "35", "45", "50", "60"]

product_last_delivered = ["2015-07-29T00:00:00.000+08:00", "2015-04-10T00:00:00.000+08:00", "2015-11-19T00:00:00.000+08:00", "2015-01-05T00:00:00.000+08:00", "2015-11-18T00:00:00.000+08:00", "2015-11-04T00:00:00.000+08:00", "2015-04-01T00:00:00.000+08:00", "2015-11-13T00:00:00.000+08:00", "2014-10-15T00:00:00.000+08:00", "2015-10-24T00:00:00.000+08:00", "1899-12-31T23:36:42.000+07:36", "2015-10-20T00:00:00.000+08:00", "2015-06-17T00:00:00.000+08:00", "2015-11-14T00:00:00.000+08:00", "2015-03-12T00:00:00.000+08:00", "2015-07-18T00:00:00.000+08:00", "2015-07-27T00:00:00.000+08:00", "2015-09-21T00:00:00.000+08:00", "2015-10-07T00:00:00.000+08:00"]

Kelvin
  • 2,218
  • 4
  • 22
  • 41

1 Answers1

2

Here are two ways of doing that. First using the native sort, the second using underscore.

Helpers.

function descending(a, b) {return b - a;}
function str2date(s) {return new Date(s);}
function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}

Using Array.prototype.sort

// To sort the grades, first eliminate the non-numbers and then sort.
product_grades.filter(isNumeric).sort(descending);

// To sort the dates, first convert strings to dates and then sort them.
product_last_delivered.map(str2date).sort(descending)

Using Underscore's _.sortBy

_.sortBy(product_grades.filter(isNumeric), descending)
_.sortBy(product_last_delivered.map(str2date), descending)

Credits.

isNumeric is from this wonderful answer by DemoUser.

Community
  • 1
  • 1
Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31