简体   繁体   English

javascript - 自定义排序返回的数据

[英]javascript - custom sort returned data

I have the following javascript and knockout js code that returns three values from an xml file: 我有以下javascript和knockout js代码从xml文件返回三个值:

 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". 返回的值(myCategories [i] .Reference)是“Best”,“Better”和“Good”。 I need to sort these values to always be "Good", "Better", "Best". 我需要将这些值排序为“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. 返回的数据没有我可以用来对它们进行排序的另一个键/字段,所以我需要以某种方式在for循环上手动执行此操作。

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. 使用sort函数并在进行比较时将字符串映射为数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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