angular2 typescript函数用于按多个字段对对象数组进行排序

时间:2017-03-28 10:16:53

标签: angular typescript ionic2

我正在尝试将this函数转换为angular2 / Typescript,以便按多个字段对对象数组进行排序。

我是打字稿的新手,你能帮我检查一下吗?

我正在打电话

prodataTemp.sort(this.UtilsService.sort_by('brand', 'name', 'model'));

并在utils-service.ts中:

sort_by(...args: any[]) { //multiple sort https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields
        var fields = [],
            n_fields = args.length,
            field, name, reverse, cmp;

        var default_cmp = function(a, b) {
            if (a == b) return 0;
            return a < b ? -1 : 1;
        };

        var getCmpFunc = function(primer, reverse) {
            var dfc = default_cmp, // closer in scope
                cmp = default_cmp;
            if (primer) {
                cmp = function(a, b) {
                    return dfc(primer(a), primer(b));
                };
            }
            if (reverse) {
                return function(a, b) {
                    return -1 * cmp(a, b);
                };
            }
            return cmp;
        };

        // preprocess sorting options
        for (var i = 0; i < n_fields; i++) {
            field = args[i];
            if (typeof field === 'string') {
                name = field;
                cmp = default_cmp;
            }
            else {
                name = field.name;
                cmp = getCmpFunc(field.primer, field.reverse);
            }
            fields.push({
                name: name,
                cmp: cmp
            });
        }

        // final comparison function
        return function(A, B) {
            var a, b, name, result;
            for (var i = 0; i < n_fields; i++) {
                result = 0;
                field = fields[i];
                name = field.name;

                result = field.cmp(A[name], B[name]);
                if (result !== 0) break;
            }
            return result;
        }
    };

谢谢!

1 个答案:

答案 0 :(得分:-1)

public class Site
{
        public Site(){}
        public string SiteId{get;set;}
        public int Value{get;set;}
}

public class HubObject
{
        public HubObject(){}
        public Site Hub{get;set;}
        public List<Site> Sites{get;set;}
}
这样做怎么样?