简体   繁体   中英

Sorting week number and year in ascending order

Is it possible to sort an array of dates with a specific format in ascending order? The format includes the year and week number, which you can see below:

Excerpt of the unsorted array:

["2014 - 03", "2013 - 01", "2013 - 02", "2014 - 03"]

Desired result of an sorted array:

["2013 - 01", "2013 - 02", "2014 - 03"]

I would like to use a compare function to implement the sorting algorithm in javascript and D3.js.

Try something like this:

var L = ["2014 - 03", "2013 - 01", "2013 - 02", "2014 - 03"]
L.sort(function(a, b){ 
    var y1 = 1 * a.split(" - ")[0],
        y2 = 1* b.split(" - ")[0],
        m1 = 1 * a.split(" - ")[1],
        m2 = 1 * b.split(" - ")[1];
    if (y1 != y2) return d3.ascending(y1, y2);
    else return d3.ascending(m1, m2);
});

You can use the built-in Array sort function to sort the array, which takes an optional function for comparing a pair of elements. You can then use d3.ascending to sort the elements in ascending order by year, or if the years are the same, by month.

Note that I'm not sure if you want to remove duplicate elements, as you did in your example. You can easily do that before or after sorting the array (see this SO answer ):

L = L.filter(function(d, i){ return L.indexOf(d) == i; })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM