我有一个包含数字和字符串的列表。
列表中的每个元素看起来像:
{
'name': 'Bob',
'number': 234234
}
但是,名字或号码可能会丢失。
在我的 sortBy 中,我做了这样的事情:
_.sortBy(list, function(element) {
if (element.name) {
return element.name;
}
else {
return element.number;
}
});
这会将带有数字的元素排在没有数字的元素前面。我如何让 lodash 降低数字的优先级?
最佳答案
我想您的意思只是 _.sortBy 按升序排列?
sortBy_.sortBy(list, iteratee, [context]) Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length).
http://underscorejs.org/#sortBy
因此,当您为 element.name
设置优先级时,它会出现在排序的最后。
您可以简单地反转结果数组
results = results.reverse();
或者,更改 if/else
语句的顺序。
关于javascript - lodash sortby,如何对字母后的数字进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468089/