This commit is contained in:
Philippe Torrel
2026-09-17 14:38:37 +02:00
parent 1e045985be
commit 67d5a1dc16
10 changed files with 506 additions and 0 deletions
@@ -0,0 +1,97 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Array - ar.reduce()</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<h1>Array - ar.reduce()</h1>
<p>
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">
ar.reduce()
</a>
- Die <strong>reduce()</strong>-Methode reduziert ein Array auf einen einzigen Wert, indem es jeweils zwei
Elemente (von links nach rechts) durch eine gegebene Funktion reduziert.
</p>
<div class="alert alert-warning">side-effect-free</div>
<div class="alert alert-secondary output"></div>
</div>
</main>
<script>
'use strict';
(() => {
const outputEl = document.querySelector('.output');
const customersOnline = ['Heribert', 'Friedlinde', 'Tusnelda', 'Oswine', 'Ladislaus'];
const names = [
'Florian', //
'Benjamin',
'Christian',
'Stefan',
'Philippe',
'Kaumon',
];
const products = [
'Game of Thrones Wax Seal Coasters',
'Electronic Butterfly in a Jar',
'Aquafarm: Aquaponics Fish Garden',
'Cassette Adapter Bluetooth',
'Marvel Comics Lightweight Infinity Scarf',
'Ollie - The App Controlled Robot',
'Sound Splash Bluetooth Waterproof Shower Speaker',
'PowerCube',
'Backpack of Holding',
'Retro Duo Portable NES/SNES Game System',
'Universal Gadget Wrist Charger',
'USB Squirming Tentacle',
'USB Fishquarium',
'Space Bar Keyboard Organizer & USB Hub Pop',
'USB Pet Rock',
'Powerstation 5- E. Maximus Chargus',
'Dual Heated Travel Mug',
'Crosley Collegiate Portable USB Turntable',
'Meh Hoodie',
'Magnetic Accelerator Cannon',
];
const cartItemPrices = [9.99, 19.99, 5.99];
// Array Methode - ar.reduce((value1, value2 [, index] [, array]) => {...}, initialValue)
const totalPrice = cartItemPrices.reduce((a, b) => {
return a + b;
}); // => 35.7
console.log([1, 2, 3, 4, 5].reduce((n1, n2) => n1 + n2)); // => 15
console.log([5].reduce((n1, n2) => n1 + n2)); // => 5
// console.log([].reduce((n1, n2) => n1 + n2)); // => Uncaught TypeError: Reduce of empty array with no initial value
// reduce mit Initialwert (RECOMMENDED)
console.log([].reduce((n1, n2) => n1 + n2, 0)); // => 0
// =======
console.log([1, 5, 10].reduce((n1, n2) => Number(n1) + Number(n2), 10)); // => 26
console.log([1, 5, 10].reduce((sum, n) => sum + Number(n), 0)); // => 16
console.log('-------');
// Optionale Parameter von forEach ========================
// Array Methode - ar.names((value1, value2 [, index [, array] ]) => {}, initialValue)
names.reduce((str, name, idx, ar) => {
console.log(`String: ${str}, Name: ${name}, Index: ${idx}, Array: ${ar.join(', ')}`);
return str + ' - ' + name;
}, '');
})();
</script>
</body>
</html>