Summary: in this tutorial, you’ll learn how to use the Dart reduce()
method to reduce a collection to a single value.
Introduction to the Dart reduce() method
The
is a method reduce()
Iterable<E>
class. Here’s the syntax of the
method:reduce()
E reduce( E combine(E value,E element))
Code language: Dart (dart)
The reduce()
method reduces a collection of elements to a single value by iteratively combining elements using a combine()
function.
The
raises an exception if the iterable has no element. Therefore, the iterable must have at least one element. Also, if the iterable has only one element, the reduce()
method returns that element.reduce()
If the iterable has multiple elements, the reduce()
method starts with the first element and combines it with the remaining elements in iteration order.
Dart reduce() method example
Suppose you have a list of numbers:
var numbers = [1, 2, 3, 4, 5];
Code language: Dart (dart)
To calculate the sum of all the numbers in the list, you can use a for-in loop like this:
void main() {
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
for (var number in numbers) {
sum += number;
}
print('sum: $sum');
}
Code language: Dart (dart)
Output:
sum: 15
Code language: Dart (dart)
This example works fine. But it’ll more concise by using the reduce()
method:
void main() {
var numbers = [1, 2, 3, 4, 5];
var sum = numbers.reduce((v, e) => v + e);
print('sum: $sum');
}
Code language: Dart (dart)
Output:
sum: 15
Code language: Dart (dart)
To understand how the reduce()
method works, we’ll use the print()
function to display the parameters of the anonymous function:
void main() {
var numbers = [1, 2, 3, 4, 5];
var sum = numbers.reduce((v, e) {
print('v=$v e=$e result=${v + e}');
var result = v + e;
return result;
});
print('sum: $sum');
}
Code language: Dart (dart)
Output:
v=1 e=2 result=3
v=3 e=3 result=6
v=6 e=4 result=10
v=10 e=5 result=15
sum: 15
Code language: Dart (dart)
In this example, the reduce()
method iterates over the elements of the numbers list. It passes the first element to the value and the second element to the element parameter. The result is 3.
From the second iteration, the reduce()
method assigns the result of the previous iteration to the value and sums it up with the next element till the last element.
Summary
- Use the
reduce()
method to reduce a collection into a single value.