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?
2 Answers
Reset to default 5Lodash'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';