Хотите понять функцию сокращения?
Я думаю, что mdn очень хорошо это определяет
Метод
reduce()
выполняет функцию редуктора (которую вы предоставляете) для каждого элемента массива, в результате чего получается одно выходное значение.
Давайте сначала сосредоточимся на функции Reducer
// Reducer, as the name says, gobbles up the current item and decides how this item is going to contribute in the end result aka accumulator and returns updated accumulator back. type Reducer = (acc: Accumulator, a: Item) => Accumulator; Few examples: const addReducer = function(acc, a) { return acc + a } const filterReducer = function (acc, a) { if(condition) { return acc + a; } else { return acc; } } // Amazing right? Hard problems can be solved by breaking it into smaller understandable pieces, while looping through a list, reducer helps you focus on the current item. // And an interesting point to note here, unlike for-loop solutions, you don't have to keep any out of context variable to store results, "accumulator" fills the need to store result
Теперь давайте посмотрим на "Уменьшить"
type reduce = (fn: Reducer, initialValueForAcc) => Accumulator //Let's use it [1,2,3,4,5].reduce(addReducer, 0) // => 15
Сравните это с циклом for
Давайте возьмем пример classRoom, в котором есть следующие ученики
Мы хотим написать программу для студентов дневного отделения по классам