js数组的多条件排序
-
先按照city排好序,再按照home进行排序,最后按照size排序
-
var data = [
{“city”: “四川”, “home”:“成都”, “size”: “1”},
{“city”: “广东”, “home”:“深圳”, “size”: “3”},
{“city”: “广东”, “home”:“广州”, “size”: “5”},
{“city”: “四川”, “home”:“自贡”, “size”: “2”},
{“city”: “广东”, “home”:“广州”, “size”: “2”}
]; -
直接撸代码
-
const moreConditionScort = function (tableData = [], fields = []) {
var arrScort = [], result = []
function getSort(fn) {
return function (a, b) {
var ret = 0
if (fn.call(this, a, b)) {
ret = -1
} else if (fn.call(this, b, a)) {
ret = 1
}
return ret
}
}
function getMutipSort(arr) {
return function (a, b) {
var tmp,
i = 0
do {
tmp = arr[i++](a, b)
} while (tmp == 0 && i < arr.length)
return tmp
}
}
for (let i = 0; i < fields.length; i++) {
arrScort.push(
getSort(function (a, b) {
return a[fields[i]] < b[fields[i]]
})
)
}
result = tableData.sort(getMutipSort(arrScort))
return result
}
let tableData = moreConditionScort(data,[‘city’,‘home’,‘size’])