ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ основному содСрТимому

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));