使用 sortBy 链接 Lodash 会产生错误,而香草排序有效

Lodash chaining with sortBy produces error while vanilla sort works

鉴于此:

let nums = [1,5,4]
let sorter = (a,b) => a.property > b.property ? 1 : -1;
let mapper = x => {return {property:x}}

这会引发错误:

_.chain(nums).map(mapper).sortBy(sorter).value()
// Uncaught TypeError: Cannot read property 'property' of undefined

虽然这不是:

nums.map(mapper).sort(sorter)
// [{"property":1},{"property":4},{"property":5}]

什么给了?我们不能保证 sortBymap 之后会 运行 吗?还是我在这里遗漏了一些真正明显的东西?

lodash带的sorter函数只有一个参数: https://lodash.com/docs/4.17.4#sortBy

https://jsfiddle.net/jq26573q/

let sorter = (o) => o.property;

尽管直接指定属性更好:

let sorter = 'property';

Lodash 的 sortBy 函数接受作为迭代器排序依据的第二个参数,并且不接受与原生 sort() 函数相同的排序函数模式。您可以将要排序的键的字符串放在:

_.chain(nums).map(mapper).sortBy('property').value()

或者传入一个指向你想要排序的 属性 的函数:

_.chain(nums).map(mapper).sortBy((o) => o.property).value()