Метод Reduce обычно используется, когда вы хотите выполнить вычисление массива и вернуть одно значение.
array.reduce(callbackFn, initialValue)
Функция обратного вызова принимает 4 параметра:
- накопитель используется для хранения значений предыдущих итераций. На первой итерации равен initialValue, если он указан, иначе первому элементу массива.
- currentValue предоставляет доступ к значению элемента в текущей итерации. Если указано initialValue, то currentValue начинается с первого элемента массива, иначе currentValue начинается со второго элемента массива.
- currentIndex дает индекс currentValue. 0, если было указано initialValue, иначе 1.
- массив дает массив, к которому применяется метод сокращения.
InitialValue используется для инициализации первого значения аккумулятора.
Примеры
Вернуть число
Используйте метод reduce(), чтобы добавить все числа в массив и вернуть сумму.
const arrayOfNumbers = [0, 1, 2, 3, 4]; const result = arrayOfNumbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; // add currentValue to accumulated sum }, 0); // 0 is initial value of accumulator console.log(result); // result 10,
Вернуть строку
Используйте reduce() для возврата всех уникальных чисел из заданного массива.
const arrayOfStrings = ["Hello", " ", "world", "!"]; const result = arrayOfStrings.reduce((accumulator, currentValue) => { // concatenate accumulator string with currentValue string return accumulator + currentValue; }, ""); // "" is initial value of accumulator console.log(result); // result "Hello world!"
Вернуть массив
Используйте reduce() для возврата всех уникальных чисел из заданного массива.
const arrayOfNumbers = [1, 2, 3, 4, 2, 3, 5, 6, 1]; const result = arrayOfNumbers.reduce( (accumulator, currentValue) => { // check if accumulator contains currentValue if (accumulator.includes(currentValue)) { // do nothing return accumulator; } else { // add currentValue to accumulator return [...accumulator, currentValue]; } }, [] ); console.log(result); // result [1, 2, 3, 4, 5, 6]
Вернуть объект
Используйте reduce() для подсчета количества голосов за каждого кандидата и возврата данных в объект.
const votes = [ { candidate: "Alice" }, { candidate: "Bob" }, { candidate: "Alice" }, { candidate: "Charlie" }, { candidate: "Bob" }, ]; const result = votes.reduce((accumulator, currentValue) => { const hasKey = accumulator.hasOwnProperty(currentValue.candidate); let count = 1; // set count 1 if first occurrence of candidate if (hasKey) { // increment count when the candidate is found in the accumulator keys count = accumulator[currentValue.candidate] += 1; } return { ...accumulator, [candidateName]: count, }; }, {}); console.log(result); // result { Alice: 2, Bob: 2, Charlie: 1 }