function orderData(data, order) { if (typeof order === 'function') return data.sort(data); if (typeof order === 'string') order = [order]; if (Array.isArray(order)) { let orderComp = []; for (let field of order) { let split = field.split(/\s+/); orderComp.push({ field: split[0], way: split[1] === 'DESC' ? -1 : 1, }); } return data.sort((a, b) => sortFunc(a, b, orderComp)); } return data; } function sortFunc(a, b, order) { for (let { field, way } of order) { let compRes = compareFunc(a[field], b[field]) * way; if (compRes !== 0) return compRes; } return 0; } function compareFunc(a, b) { if (a === b) return 0; let aType = typeof a; if (aType === typeof b) { switch (aType) { case 'string': return a.localeCompare(b); case 'number': return a - b; case 'boolean': return a ? 1 : -1; case 'object': if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime(); } } if (a === undefined) return -1; if (b === undefined) return 1; if (a === null) return -1; if (b === null) return 1; return a > b ? 1 : -1; } export default orderData;