RxJS - 數學運算子 Reduce
在 reduce 運算子中,在輸入可觀察物件中使用累加器函式,而且累加器函式將以可觀察物件的格式返回累加的值,其中有一個可選的種子值傳給累加器函式。
reduce() 函式將輸入 2 個引數,一個累加器函式,第二個是種子值。
語法
reduce(accumulator_func, seeder?) : Observable
引數
accumulator_func − (可選)。呼叫可觀察物件中源值的函式。
seeder − ((可選) 預設值是未定義。考慮累加的初始值。
返回值
它將返回具有單個累加值的可觀察物件。
我們來看一些示例,瞭解 reduce 運算子是如何工作的。
示例 1
import { from } from 'rxjs';
import { reduce } from 'rxjs/operators';
let items = [
{item1: "A", price: 1000.00},
{item2: "B", price: 850.00},
{item2: "C", price: 200.00},
{item2: "D", price: 150.00}
];
let final_val = from(items).pipe(reduce((acc, itemsdet) => acc+itemsdet.price, 0));
final_val.subscribe(x => console.log("Total Price is: "+x));
輸出
Total Price is: 2200
廣告