对象数组,某个key的值进行排序

        function compare(key: string, order: string) {
            return function (value1: any, value2: any) {
                var val1 = value1[key]
                var val2 = value2[key]
                switch (order) {
                    // 升序
                    case 'ascending':
                        if (typeof val1 === 'number') {
                            return val1 - val2
                        } else if (typeof val1 === 'string') {
                            return val1.localeCompare(val2)
                        }
                        break
                    // 降序
                    case 'descending':
                        if (typeof val1 === 'number') {
                            return val2 - val1
                        } else if (typeof val1 === 'string') {
                            return val2.localeCompare(val1)
                        }
                        break
                    default:
                        break
                }
            }
        }

你可能感兴趣的:(对象数组,某个key的值进行排序)