W3cubDocs

/Dart 2

reduce method

E reduce (E combine(E previousValue, E element))

Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

The iterable must have at least one element. If it has only one element, that element is returned.

Otherwise this method starts with the first element from the iterator, and then combines it with the remaining elements in iteration order, as if by:

E value = iterable.first;
iterable.skip(1).forEach((element) {
  value = combine(value, element);
});
return value;

Example of calculating the sum of an iterable:

iterable.reduce((value, element) => value + element);

Implementation

E reduce(E combine(E previousValue, E element)) {
  int length = this.length;
  if (length == 0) throw IterableElementError.noElement();
  E value = this[0];
  for (int i = 1; i < length; i++) {
    value = combine(value, this[i]);
    if (length != this.length) {
      throw new ConcurrentModificationError(this);
    }
  }
  return value;
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/2.0.0/dart-collection/ListMixin/reduce.html