underscorejs-sortBy学习

2.17 sortBy

2.17.1 语法

_.sortBy(list, iteratee, [context])

2.17.2 说明

返回一个排序后的list拷贝副本。

  • list为集合,如数组、对象、字符串、arguments等
  • iteratee为排序的依据,可以为function,元素的属性、元素的key也可以全局方法。
  • iteratee也可以不传
  • iteratee的参数为(value, key, list)
  • iteratee如果是function需要返回值
  • context可以改变iteratee内部的this
  • 返回的结果是list的副本

2.17.3 代码示例

示例一: 比较适合于数组的元素是对象,进行排序

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为排序的依据

上例的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"]

示例三:list为集合

//数组
_.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));

示例四:iteratee的参数

_.sortBy(['a', 'b'], function(value, key, list){
    console.log(value, key, list);
    //=> a 0 ["a", "b"]
    //=> b 1 ["a", "b"]
    return value;
});

示例五:context可以改变iteratee内部的this

_.sortBy(['a'], function(value, key, list){
    console.log(this); //=> Object {text: "hello"}
    return value;
}, {text : 'hello'});

示例六: 返回的结果是list的副本

var list = ['1112', '222'];
var result = _.sortBy(list, 'length');

//list没有被改变
console.log(list); //=> ["1112", "222"]
console.log(result); //=> ["222", "1112"]

2.17.4 list特殊情况返回空数组

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));

2.17.5 和_.map的对比

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]

2.17.6 请将列表按at的值倒序输出(坑)

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}]

2.17.7 请将列表按stopDate的值排序输出。(坑)

不管是正序或倒序,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));
原文地址:https://www.cnblogs.com/kyo4311/p/5176215.html