var obj = [{
id : 1,
age : 20,
top :5
},{
id : 3,
age : 21,
top : 6
},{
id : 2,
age : 20,
top : 8
}]
function keysort(property) {
return function(a, b) {
var value1 = a[property] == '-' ? 0 : a[property];
var value2 = b[property] == '-' ? 0 : b[property];
return value1 - value2;
}
}
var obj1 = obj.sort(keysort('age'));
寫一半 不會寫了 age相同的情況下 再按照top從高到低排序 想請教下老司機(jī)
認(rèn)證0級講師
This is so long-winded...
obj.sort( function(curr,next) {
return !!( curr.age-next.age )? curr.age-next.age: curr.top-next.top;
} );
Isn’t this great?
Just use what you bring
obj = obj.sort((a, b) => { return a.age - b.age || b.top - a.top;} );
console.log(obj);
Because you are talking about sorting top from high to low. This way of writing means that the larger the number, the higher it is. If you want the smaller number to be smaller, just change the position b.top - a.top to a.top - b.top
Online experience https://jsfiddle.net/hguyjgs8/1/
//假設(shè)top 不大于1000, 大于1000的,適度修改
var obj = [{
id: 1,
age: 20,
top: 5
}, {
id: 3,
age: 21,
top: 6
}, {
id: 2,
age: 20,
top: 8
}]
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
obj.sort((a, b) => pad(a.age, 2) + pad(1000-a.top, 3) > pad(b.age, 2) + pad(1000-b.top, 3)).forEach((i) => {
document.writeln(JSON.stringify(i)+'<br>');
});
function keySort (...args) {
let props = args.map(name => {
let desc = name[0] === '-'
if (desc) name = name.substring(1)
return { desc, name }
})
return (a, b) => {
let result = 0
for (let prop of props) {
let p = prop.name
result = prop.desc ? b[p] - a[p] : a[p] - b[p]
if (result) return result
}
return result
}
}
obj.sort(keySort('age', '-top'))
https://jsfiddle.net/sojxjqpf/
var whoFirst = ['age', 'top'];
var copy = o => JSON.parse(
JSON.stringify(o)
);
var judge = (a, b, whos) => {
if (whos.length === 0) return 0;
let key = whos[0];
if (a[key] !== b[key]){
return a[key] - b[key];
} else {
return judge(a, b, whos.slice(1));
}
}
var sorts = arr => {
let a = copy(arr);
a.sort((a, b) => {
return judge(a, b, whoFirst);
});
return a;
}
WhoFirst 升序。
var obj = [{
id : 1,
age : 20,
top :5
},{
id : 3,
age : 21,
top : 6
},{
id : 2,
age : 20,
top : 8
},{
id: 4,
age: 20,
top: 2
},{
id: 8,
age: 20,
top: 2
},{
id: 5,
age: 20,
top: 11
},{
id: 7,
age: 20,
top: 9
},{
id: 6,
age: 20,
top: 2
},{
id: 9,
age: 20,
top: 1
}];
sorts(obj);