简体   繁体   中英

javascript - custom sort returned data

I have the following javascript and knockout js code that returns three values from an xml file:

 var populateCategories = function (myId, mySize) {
    self.categoryOptions([]); //Empty the observable array
    var myCategories = getCategories(myId);
    var i = null;
    for (i = 0; myCategories.length > i; i += 1) {
        if (myCategories[i].ProductSize == mySize) {
            self.categoryOptions.push({ "label": myCategories[i].Reference });
        }
    }

The returned values (myCategories[i].Reference), are "Best", "Better", and "Good". I need to sort these values to always be "Good", "Better", "Best". Sorting alphabetically will not work as it will return "Good", "Best", "Better".

The returned data does not have another key/field that I can use to sort them by, so I need to somehow do this manually on the for loop.

How can I sort the data so that the end result is "Good", "Better", "Best"?

Use the sort function and map your strings into numbers when doing the comparison.

self.categoryOptions.sort(function(a,b){
   var values = {Good: 0, Better: 1, Best: 2};
   return values[a.label] - values[b.label];
});

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