返回介绍

sortBy

发布于 2019-05-31 13:13:01 字数 2687 浏览 1222 评论 0 收藏 0

Creates a new sequence with the same elements as this one, but ordered by the results of the given function.

You can pass:

  • a string, to sort by the named property
  • a function, to sort by the result of calling the function on each element

Signature

Sequence.sortBy = function(sortFn, descending) { /*...*/ }
Sequence.sortBy = function sortBy(sortFn, descending) {
  sortFn = createComparator(sortFn);
  if (descending) { sortFn = reverseArguments(sortFn); }
  return new SortedSequence(this, sortFn);
}
NameType(s)Description
sortFnFunction

The function to call on the elements in this sequence, in order to sort them.

descendingboolean

Whether or not the resulting sequence should be in descending order (defaults to false).

returnsSequence

The new sequence.

Examples

function population(country) {
  return country.pop;
}

function area(country) {
  return country.sqkm;
}

var countries = [
  { name: "USA", pop: 320000000, sqkm: 9600000 },
  { name: "Brazil", pop: 194000000, sqkm: 8500000 },
  { name: "Nigeria", pop: 174000000, sqkm: 924000 },
  { name: "China", pop: 1350000000, sqkm: 9700000 },
  { name: "Russia", pop: 143000000, sqkm: 17000000 },
  { name: "Australia", pop: 23000000, sqkm: 7700000 }
];

Lazy(countries).sortBy(population).last(3).pluck('name') // sequence: ["Brazil", "USA", "China"]
Lazy(countries).sortBy(area).last(3).pluck('name')       // sequence: ["USA", "China", "Russia"]
Lazy(countries).sortBy(area, true).first(3).pluck('name') // sequence: ["Russia", "China", "USA"]

Benchmarks

var randoms = Lazy.generate(Math.random).take(100).toArray();

Lazy(randoms).sortBy(Lazy.identity).each(Lazy.noop) // lazy
_.each(_.sortBy(randoms, Lazy.identity), _.noop)    // lodash
ImplementationOps/second
lazy
lodash

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文