sortedByValue method

List<T> sortedByValue(
  1. Comparable key(
    1. T e
    ), {
  2. bool reversed = false,
})

Returns a new list sorted based on the values derived from the given key function.

The key function is used to extract a comparable value from each element. The list is sorted in ascending order based on these derived values.

By default, the list is returned in ascending order. Use the optional reversed parameter to specify whether the list should be returned in descending order.

Returns a new list sorted based on the derived values.

Example:

class Person {
  final String name;
  final int age;

  Person(this.name, this.age);
}

List<Person> persons = [
  Person('Alice', 25),
  Person('Bob', 30),
  Person('Charlie', 20),
];

List<Person> sortedList = persons.sortedByValue((person) => person.age);
print(sortedList.map((person) => person.name).toList()); // Output: [Charlie, Alice, Bob]

Implementation

List<T> sortedByValue(Comparable key(T e), {bool reversed = false}) {
  Iterable<T> items = this.toList()..sort((a, b) => key(a).compareTo(key(b)));
  return reversed ? items.reversed.toList() : items.toList();
}