乐趣区

关于javascript:js按照数组中对象的某个属性排序

1. 代码

// 排序数组里对象是依照字母排序的
        Compare(ticked, name) {return function(a, b) {var t1 = a[ticked];
                var s1 = a[name];
                var t2 = b[ticked];
                var s2 = b[name];
                if (t1) {if (t2) {return s1.localeCompare(s2);
                    } else {return -1;}
                } else {if (!t2) {return s1.localeCompare(s2);
                    } else {return 1;}
                }
            }
        },

2. 应用办法

var arr5 = [{
            id: 10,
            first:'a'
        }, {
            id: 5,
            first:'f'
        }, {
            id: 6,
            first:'j'
        }, {
            id: 9,
            first:'e'
        }, {
            id: 2,
            first:'b'
        }, {
            id: 3,
            first:'p'
        }];
        let arr = arr5.sort(this.Compare('first', 'first'))
退出移动版