最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash chaining with sortBy produces error while vanilla sort works - Stack Overflow

programmeradmin2浏览0评论

Given this:

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

This throws an error:

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

While this does not:

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

What gives? Are we not guaranteed that sortBy will run after map? Or am I missing something truly obvious here?

Given this:

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

This throws an error:

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

While this does not:

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

What gives? Are we not guaranteed that sortBy will run after map? Or am I missing something truly obvious here?

Share asked Mar 14, 2017 at 19:34 cgsdcgsd 1,3532 gold badges14 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Lodash's sortBy function accepts as a second argument the iteratees to sort by, and doesn't accept the same pattern of sort function that the native sort() function does. You can just place in the string of the key you want to sort on:

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

Or pass in a function that points to the property you want to sort on:

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

The sorter function that lodash takes only has one parameter: https://lodash./docs/4.17.4#sortBy

https://jsfiddle/jq26573q/

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

Although even better is to specify the attribute directly:

let sorter = 'property';
发布评论

评论列表(0)

  1. 暂无评论