当前位置: 首页 > 文档资料 > Lazy.js 英文文档 >

sortBy

优质
小牛编辑
133浏览
2023-12-01

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