reduce()
reduce()β
Π€ΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ "Π‘ΠΠΠ ΠΠ§ΠΠΠΠΠΠ―" ΠΌΠ°ΡΡΠΈΠ²Π° Π² ΠΎΠ΄Π½ΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ (ΡΡΠΌΠΌΠΈΡΠΎΠ²Π°Π½ΠΈΠ΅). ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ number. preVal - ΠΏΡΠ΅Π΄ΡΠ΄ΡΡΠΈΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ. 0 - Π²ΡΠΎΡΠΎΠΉ Π°ΡΠ³ΡΠΌΠ΅Π½Ρ Π½Π΅ΠΎΠ±ΡΠ·Π°ΡΠ΅Π»ΡΠ½ΡΠΉ (ΠΠΠ§ΠΠΠ¬ΠΠΠ ΠΠΠΠ§ΠΠΠΠ).
const arr = [1, 2, 3];
const arrCount = arr.reduce((preVal, item) => {
// ΡΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ²
return preVal + item;
}, 0);
// ΡΡΠΌΠΌΠ° ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² ΠΌΠ°ΡΡΠΈΠ²Π°
console.log(arrCount); // 6
ΠΡΡΠΈΡΠ»ΠΈΡΡ ΡΡΠΌΠΌΡ
const a = [1, 2, 3, 4, 5, 6, 7, 8];
// summ = 36
const summ = a.reduce((prev, item, index) => {
return prev + item;
});
const a = [1, 2, 3, 4, 5];
// first or pre item
a.reduce(preVal => preVal); // 1
// last item
a.reduce((preVal, nextVal) => nextVal); // 5
// iteratiions count
a.reduce((preVal, nextVal, iteratiions, sourceArray) => iteratiions); // 4 (1+2, 2+3, 3+4, 4+5)
// source array
a.reduce((preVal, nextVal, iteratiions, sourceArray) => sourceArray); // [1, 2, 3, 4, 5]
// arguments naming
a.reduce((preVal, nextVal, iteratiions, sourceArray));
// sum
const sum = a.reduce((preVal, nextVal) => preVal + nextVal);
// max value
const max = a.reduce((preVal, nextVal) => Math.max(preVal, nextVal)); // 5
// min value
const min = a.reduce((preVal, nextVal) => Math.min(preVal, nextVal)); // 1
Π‘ΡΡΡ reduce Π²Π΅ΡΠ½ΡΡΡ Π½Π΅ ΠΏΡΠΎΡΡΠΎ ΠΌΠ°ΡΡΠΈΠ² ΠΊΠ°ΠΊ ΡΡΠΎ Π΄Π΅Π»Π°Π΅Ρ .map(), .filter(), .sort(), Π° Π²Π΅ΡΠ½ΡΡΡ ΠΊΠ°ΠΊΠΎΠΉ-ΡΠΎ Π²ΡΡΠΈΡΠ»ΡΠ΅ΠΌΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅, ΠΊΠΎΡΠΎΡΠΎΠ΅ ΠΏΡΠΈΠ½ΠΈΠΌΠ°Π΅ΡΡΡ Π² ΠΊΠ°ΡΠ΅ΡΡΠ²Π΅ ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ Π°ΡΠ³ΡΠΌΠ΅Π½ΡΠ°, ΠΈ ΡΠ°ΠΌ ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ Π»ΡΠ±ΠΎΠΉ ΡΠΈΠΏ Π΄Π°Π½Π½ΡΡ .
ΠΠΎΠ΄ΡΡΠ΅Ρ ΡΡΠΌΠΌΡ ΡΠΈΠΊΠ»ΠΎΠΌ for.β
const array = [1, 2, 3, 4, 5];
let summOfArray = 0;
for (i = 0; i < array.length; i++) {
summOfArray += array[i];
}
ΠΠΎΠ΄ΡΡΠ΅Ρ ΡΡΠΌΠΌΡ ΡΠ΅ΡΠ΅Π· reduce();β
const array = [1, 2, 3, 4, 5];
const summOfArray = array.reduce((total, item) => (total += item));
const array = [1, 2, 3, 4, 5];
// total ΠΏΠΎ ΡΠΌ. ΡΠ°Π²Π΅Π½ 1-ΠΎΠΌΡ ΡΠ»Π΅ΠΌΠ΅Π½ΡΡ ΠΌΠ°ΡΡΠΈΠ²Π°, Π΅ΡΠ»ΠΈ Π½Π΅ ΡΠΊΠ°Π·Π°Π»ΠΈ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ Π² ΠΊΠΎΠ½ΡΠ΅, ΠΏΡΠΈ ΡΡΠΎΠΌ Π² ΡΠΈΠΊΠ»Π΅ Π±ΡΠ΄Π΅Ρ ΠΏΡΠΎΠΏΡΡΠ΅Π½Π° ΠΏΠ΅ΡΠ²Π°Ρ ΠΈΡΠ΅ΡΠ°ΡΠΈΡ
// ΠΏΡΠΎΠ±Π΅ΠΆΠ°ΡΡΡΡ ΡΠΈΠΊΠ»ΠΎΠΌ ΠΏΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°ΠΌ
// total ΠΎΠ½ ΠΆΠ΅ accumulator, accum, item ΠΎΠ½ ΠΆΠ΅ curEl
array.reduce((total, item, index, sourceArray) => {
console.log('item', item);
}, 0); // 0 - total - Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅
// ΠΏΠΎΡΡΠΈΡΠ°ΡΡ ΡΡΠΌΠΌΡ
const summOfArray = array.reduce((total, item, index, sourceArray) => {
total += item;
return total;
}, 0);
Π total ΠΌΠΎΠΆΠ½ΠΎ Π΄Π΅ΡΠΆΠ°ΡΡ Π½Π΅ ΡΠΎΠ»ΡΠΊΠΎ number, a ΡΠ°ΠΊΠΆΠ΅ {} ΠΈ [];
ΠΠ°ΠΊΡ. Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ ΡΠΈΠΊΠ» forβ
const array = [1, 2, 3, 4, 5];
let max = array[0];
for (let i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
ΠΠ°ΠΊΡ. Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ ΡΠΈΠΊΠ» reduce()β
const array = [1, 2, 3, 4, 5];
const max = array.reduce((total, item) => Math.max(item));