欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

underscore.js的排序扩展。 倒序和多列排序 有大用

underscore.js的排序扩展。 倒序和多列排序

   // Sort the object's values by a criterion produced by an iterator.
    _.sortBy = function (obj, iterator, context) {
        iterator = lookupIterator(iterator, context);
        return _.pluck(_.map(obj, function (value, index, list) {
            return {
                value: value,
                index: index,
                criteria: iterator(value, index, list)
            };
        }).sort(function (left, right) {
            var a = left.criteria;
            var b = right.criteria;
            if (a !== b) {
                if (a > b || a === void 0) return 1;
                if (a < b || b === void 0) return -1;
            }
            return left.index - right.index;
        }), 'value');
    };
    // Sort the object's values by a criterion produced by an iterator.
    _.sortByDesc = function (obj, iterator, context) {
        iterator = lookupIterator(iterator, context);
        return _.pluck(_.map(obj, function (value, index, list) {
            return {
                value: value,
                index: index,
                criteria: iterator(value, index, list)
            };
        }).sort(function (left, right) {
            var a = left.criteria;
            var b = right.criteria;
            if (a !== b) {
                if (a > b || a === void 0) return -1;
                if (a < b || b === void 0) return 1;
            }
            return left.index - right.index;
        }), 'value');
    };
  
  _.multisortBy = function (obj, iterator, context) {
        return _.pluck(
            _.map(obj, function (value, index, list) {
                return {
                    value: value,
                    criteria: iterator.call(context, value, index, list)
                }
            }).sort(function (left, right) {
            var a = left.criteria, b = right.criteria;
            if (!$.isArray(a)) {
                return a < b ? -1 : a > b ? 1 : 0;
            } else {
                var result = 0;
                for (var i = 0 ; i < a.length ; i++) {
                    var r = a[i] < b[i] ? -1 : a[i] > b[i] ? 1 : 0;
                    if (r != 0 || i == a.length - 1)
                        return r;
                }
            }
        }), 'value');
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于 


普通分类: