UNPKG

fenzhi-utils

Version:

分值前端项目的js函数库

46 lines (42 loc) 2 kB
/** * 对一个由对象组成的数组进行排序 * @param {Array} arr arr 要排序的数组 * @param {String} prop 要排序的属性名 * @param {String} order 排序方式,默认为降序排序 * @returns {Array<Object>} 排序后的数组 */ /* // 测试数组 const list = [ { id: 6, name: 'John', age: true, score: 70.5, active: true }, { id: 5, name: '', age: '20', score: 80.5, active: false }, { id: 9, name: 'Amy', age: '20', score: 80.5, active: true }, { id: 15, name: 'Ian', age: '20', score: 80.5, active: false }, { id: 8, name: 'Lucy', age: '25', score: 75.5, active: false }, { id: 13, name: 'Grace', age: '30', score: 75.5, active: true }, { id: 2, name: 'Jerry', age: '20', score: 85.5, active: false }, { id: 3, name: 'Bob', age: '30', score: 85.5, active: true }, { id: 10, name: 'Frank', age: '30', score: 85.5, active: true }, { id: 11, name: 'David', age: '', score: 85.5, active: false }, { id: 4, name: 'Alice', age: '25', score: '', active: true }, { id: 14, name: 'Henry', age: '25', score: 85.5, active: true }, { id: 1, name: 'Tom', age: '25', score: 90.5, active: true }, { id: 12, name: 'Eva', age: '20', score: 90.5, active: true }, { id: 7, name: 'Mike', age: '30', score: 85.5, active: true }, ]; console.log(CustomArraySort(list, 'age', 'desc')); */ export function CustomArraySort(arr, prop, order = 'desc') { if (!Array.isArray(arr)) return arr; if (typeof prop !== 'string' || !prop.trim()) return arr; if (!['asc', 'desc'].includes(order)) return arr; const compare = (a, b) => (order === 'asc' ? a - b : b - a); return arr.sort((a, b) => { if (isNaN(parseFloat(a[prop]))) return 1; if (isNaN(parseFloat(b[prop]))) return -1; const aValue = parseFloat(a[prop]); const bValue = parseFloat(b[prop]); if (aValue === bValue) return arr.indexOf(a) - arr.indexOf(b); return compare(aValue, bValue); }); }