The `reduce` method in Dart reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
The syntax of Runes.reduce() method is:
int reduce(int combine(int value int element))
This reduce() method of Runes reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
Parameter | Optional/Required | Description |
---|---|---|
combine | required | A function that takes an integer value and an integer element, and returns the new combined value. |
Runes.reduce() returns value of type int
.
In this example,
numbers
containing integers.reduce()
method with a function that adds each element to the accumulated value.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
int sum = numbers.reduce((value, element) => value + element);
print(sum);
}
15
In this example,
words
containing strings.reduce()
method with a function that concatenates each word to the accumulated value with a space.void main() {
List<String> words = ['hello', 'world'];
String combined = words.reduce((value, word) => value + ' ' + word);
print(combined);
}
hello world
In this example,
uniqueNumbers
containing integers.reduce()
method with a function that multiplies each element to the accumulated value.void main() {
Set<int> uniqueNumbers = {1, 2, 3};
int product = uniqueNumbers.reduce((value, number) => value * number);
print(product);
}
6
In this Dart tutorial, we learned about reduce() method of Runes: the syntax and few working examples with output and detailed explanation for each example.