_.sortBy(list, iteratee, [context])
返回一个排序后的list拷贝副本。
var stooges = [{name: 'moe', age: 60}, {name: 'larry', age: 40}, {name: 'curly', age: 50}];
var result = _.sortBy(stooges, 'age');
console.log(result);
//=> [{age: 40, name: 'larry'}, {age: 50, name: 'curly'}, {age: 60, name: 'moe'}]
上例的iteratee对list元素的key,也可以是list元素的属性,或全局的方法。
var list = ['2.00', '1.000', '3.0', '-4'];
// iteratee为全局的方法
var arr1 = _.sortBy(list, Math.abs);
console.log(arr1) //=> ["1.000", "2.00", "3.0", "-4"]
// iteratee为元素的属性
var arr2 = _.sortBy(list, 'length');
console.log(arr2); //=> ["-4", "3.0", "2.00", "1.000"]
//数组
_.sortBy([1, 4, 7, 10, -2]); //=> [-2, 1, 4, 7, 10]
//对象
_.sortBy({a: -2, b: 1, c: 4}); //=>[-2, 1, 4]
//字符串
_.sortBy('45123'); //=>["1", "2", "3", "4", "5"]
//arguments
(function(){
_.sortBy(arguments); //=>[-2, 1, 4]
}(-2, 1, 4));
_.sortBy(['a', 'b'], function(value, key, list){
console.log(value, key, list);
//=> a 0 ["a", "b"]
//=> b 1 ["a", "b"]
return value;
});
_.sortBy(['a'], function(value, key, list){
console.log(this); //=> Object {text: "hello"}
return value;
}, {text : 'hello'});
var list = ['1112', '222'];
var result = _.sortBy(list, 'length');
//list没有被改变
console.log(list); //=> ["1112", "222"]
console.log(result); //=> ["222", "1112"]
console.log(_.sortBy(null));
console.log(_.sortBy(NaN));
console.log(_.sortBy(undefined));
console.log(_.sortBy({}));
console.log(_.sortBy(''));
console.log(_.sortBy(true));
console.log(_.sortBy(false));
var list = [undefined, 4, 1, undefined, 3, 2];
var arr1 = _.map(list, function(){
});
var arr2 = _.sortBy(list, function(){
});
console.log(arr1); //=>[undefined, undefined, undefined, undefined, undefined, undefined]
console.log(arr2); //=>[undefined, 4, 1, undefined, 3, 2]
var list = [{
title : 1,
at : 1452691455595
},{
title : 3,
at : 1452691505847
},{
title : 2,
at : 1452691505347
}];
var result = (function(list){
//请写下你的代码
}(list));
console.log(result);
//=> [{title:3, at:1452691505847},{title:2, at: 1452691505347},{title:1, at:1452691455595}]
不管是正序或倒序,stopDate的值null的时候,统一放在后面。
var list = [{
"id": "0",
"stopDate": null
}, {
"id": "1",
"stopDate": "10/06/2014"
}, {
"id": "2",
"stopDate": null
}, {
"id": "3",
"stopDate": "09/06/2014"
}];
var asc = (function (list) {
//请写下你的代码
}(list));
var desc = (function (list) {
//请写下你的代码
}(list));