const items = [
{ name: 'linc', age: 28, num: 1234 },
{ name: 'linc', age: 28, num: 12345 },
{ name: 'kiki', age: 20, num: 12345 },
{ name: 'Jim', age: 26, num: 123, other: 100 },
{ name: 'Jim', age: 27, num: 101 },
{ name: 'Jim', age: 26, num: 111, other: 99 },
{ name: 'Andy', age: 29, num: 110 },
{ name: 'Andy', age: 30, num: 110 },
// 不定义排序方向和字段,默认所有字段升序排列
items.sort((a, b) => sortByProps(a, b))
console.log(items)
// 两个字段一升一降排序
// items.sort((a, b) => sortByProps(a, b, { name: 'asc', age: 'desc' }))
// 定义多个字段排序
// items.sort((a, b) => sortByProps(a, b, { name: 'asc', age: 'desc', other: 'asc' }))
// 两个字段都降序排序,其他排序方向同理,也可再加字段
// items.sort((a, b) => sortByProps(a, b, { name: 'desc', age: 'desc' }))
sortByProps方法如下:
function sortByProps(item1, item2, props) {
const isValid = props && Object.prototype.toString.call(props) === '[object Object]'
const cps = []
let asc = true
if (!isValid) {
for (let p in item1) {
if (item1[p] > item2[p]) {
cps.push(1)
break
} else if (item1[p] === item2[p]) {
cps.push(0)
} else {
cps.push(-1)
break
} else {
for (let o in props) {
asc = props[o] === 'asc'
if (item1[o] > item2[o]) {
cps.push(asc ? 1 : -1)
break
} else if (item1[o] === item2[o]) {
cps.push(0)
} else {
cps.push(asc ? -1 : 1)
break
for (let j = 0; j < cps.length; j++) {
if (cps[j] === 1 || cps[j] === -1) {
return cps[j]
return false
来自:js自定义多字段排序