Anfänger182025-01-15

JavaScript Arrays - Listen & Array Methods

Lerne JavaScript Arrays: Erstellung, Zugriff, push, pop, map, filter, reduce, forEach, find, spread, destructuring und Best Practices.

#javascript#arrays#map#filter#reduce#array-methods

JavaScript Arrays

Arrays sind geordnete Listen von Werten. Perfekt um mehrere Daten zu speichern!

Was sind Arrays?

Arrays speichern mehrere Werte in einer Variable:

Array Basics
// Ohne Array (mühsam!)
const name1 = 'Max';
const name2 = 'Anna';
const name3 = 'Tom';

// Mit Array (elegant!)
const namen = ['Max', 'Anna', 'Tom'];

console.log(namen);  // ['Max', 'Anna', 'Tom']
console.log(namen[0]);  // Max
console.log(namen[1]);  // Anna
console.log(namen[2]);  // Tom

Eigenschaften:

  • ✅ Geordnet (Index beginnt bei 0)
  • ✅ Beliebig viele Elemente
  • ✅ Verschiedene Typen möglich
  • ✅ Dynamische Größe

Array erstellen

Array Creation
// Array Literal (am häufigsten)
const zahlen = [1, 2, 3, 4, 5];
const namen = ['Max', 'Anna', 'Tom'];
const mixed = [1, 'text', true, null];

// Leeres Array
const leer = [];

// Array Constructor (selten)
const arr = new Array(5);  // [undefined × 5]
const arr2 = new Array(1, 2, 3);  // [1, 2, 3]

// Von String
const text = 'Hallo';
const buchstaben = text.split('');  // ['H', 'a', 'l', 'l', 'o']

// Von Zahlenbereich
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(numbers);  // [1, 2, 3, 4, 5]

Auf Elemente zugreifen

Array Access
const namen = ['Max', 'Anna', 'Tom', 'Lisa'];

// Über Index (startet bei 0)
console.log(namen[0]);  // Max
console.log(namen[1]);  // Anna
console.log(namen[3]);  // Lisa

// Letztes Element
console.log(namen[namen.length - 1]);  // Lisa

// Negativ (nicht direkt, aber so)
console.log(namen[namen.length - 2]);  // Tom

// at() Method (moderner)
console.log(namen.at(0));   // Max
console.log(namen.at(-1));  // Lisa (von hinten!)
console.log(namen.at(-2));  // Tom

Array-Länge

length Property
const namen = ['Max', 'Anna', 'Tom'];

console.log(namen.length);  // 3

// Länge nutzen
for (let i = 0; i < namen.length; i++) {
    console.log(namen[i]);
}

// Prüfen ob leer
if (namen.length === 0) {
    console.log('Array ist leer');
}

// Length ändern (vorsicht!)
namen.length = 2;
console.log(namen);  // ['Max', 'Anna'] (Tom gelöscht!)

namen.length = 5;
console.log(namen);  // ['Max', 'Anna', undefined, undefined, undefined]

Elemente hinzufügen

push() - Am Ende hinzufügen

push Method
const namen = ['Max', 'Anna'];

namen.push('Tom');
console.log(namen);  // ['Max', 'Anna', 'Tom']

namen.push('Lisa', 'Ben');
console.log(namen);  // ['Max', 'Anna', 'Tom', 'Lisa', 'Ben']

// push gibt neue Länge zurück
const länge = namen.push('Sarah');
console.log(länge);  // 6

unshift() - Am Anfang hinzufügen

unshift Method
const namen = ['Max', 'Anna'];

namen.unshift('Tom');
console.log(namen);  // ['Tom', 'Max', 'Anna']

namen.unshift('Lisa', 'Ben');
console.log(namen);  // ['Lisa', 'Ben', 'Tom', 'Max', 'Anna']

splice() - An bestimmter Position

splice zum Hinzufügen
const namen = ['Max', 'Anna', 'Tom'];

// An Index 1 einfügen
namen.splice(1, 0, 'Lisa');
console.log(namen);  // ['Max', 'Lisa', 'Anna', 'Tom']

// Mehrere einfügen
namen.splice(2, 0, 'Ben', 'Sarah');
console.log(namen);  // ['Max', 'Lisa', 'Ben', 'Sarah', 'Anna', 'Tom']

Elemente entfernen

pop() - Letztes Element entfernen

pop Method
const namen = ['Max', 'Anna', 'Tom'];

const letzter = namen.pop();
console.log(letzter);  // Tom (entferntes Element)
console.log(namen);    // ['Max', 'Anna']

namen.pop();
console.log(namen);  // ['Max']

shift() - Erstes Element entfernen

shift Method
const namen = ['Max', 'Anna', 'Tom'];

const erster = namen.shift();
console.log(erster);  // Max
console.log(namen);   // ['Anna', 'Tom']

splice() - An bestimmter Position

splice zum Entfernen
const namen = ['Max', 'Anna', 'Tom', 'Lisa'];

// 1 Element ab Index 1 entfernen
namen.splice(1, 1);
console.log(namen);  // ['Max', 'Tom', 'Lisa']

// 2 Elemente ab Index 1 entfernen
namen.splice(1, 2);
console.log(namen);  // ['Max']

Array Methods Übersicht

Add/Remove Methods
const arr = [1, 2, 3];

// Am Ende
arr.push(4);        // [1, 2, 3, 4]
arr.pop();          // [1, 2, 3]

// Am Anfang
arr.unshift(0);     // [0, 1, 2, 3]
arr.shift();        // [1, 2, 3]

// In der Mitte
arr.splice(1, 0, 1.5);  // [1, 1.5, 2, 3] (einfügen)
arr.splice(1, 1);       // [1, 2, 3] (entfernen)

slice() - Kopie/Teil eines Arrays

Verändert Original NICHT:

slice Method
const zahlen = [1, 2, 3, 4, 5];

// Von Index 1 bis 3 (exklusiv)
const teil = zahlen.slice(1, 3);
console.log(teil);    // [2, 3]
console.log(zahlen);  // [1, 2, 3, 4, 5] (Original unverändert)

// Ab Index 2
const ab2 = zahlen.slice(2);
console.log(ab2);  // [3, 4, 5]

// Letzten 2
const letzten2 = zahlen.slice(-2);
console.log(letzten2);  // [4, 5]

// Kopie erstellen
const kopie = zahlen.slice();
console.log(kopie);  // [1, 2, 3, 4, 5]

concat() - Arrays verbinden

concat Method
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const verbunden = arr1.concat(arr2);
console.log(verbunden);  // [1, 2, 3, 4, 5, 6]

// Mehrere Arrays
const arr3 = [7, 8];
const alle = arr1.concat(arr2, arr3);
console.log(alle);  // [1, 2, 3, 4, 5, 6, 7, 8]

// Mit einzelnen Werten
const result = arr1.concat(4, 5);
console.log(result);  // [1, 2, 3, 4, 5]

indexOf() & includes() - Element finden

indexOf & includes
const namen = ['Max', 'Anna', 'Tom', 'Anna'];

// indexOf - Gibt Index zurück
console.log(namen.indexOf('Anna'));  // 1 (erster Treffer)
console.log(namen.indexOf('Lisa'));  // -1 (nicht gefunden)

// includes - Gibt Boolean zurück
console.log(namen.includes('Tom'));   // true
console.log(namen.includes('Lisa'));  // false

// Mit Startposition
console.log(namen.indexOf('Anna', 2));  // 3 (ab Index 2)

// Praktisch in Bedingungen
if (namen.includes('Max')) {
    console.log('Max ist dabei!');
}

join() - Array zu String

join Method
const namen = ['Max', 'Anna', 'Tom'];

// Mit Komma (Standard)
console.log(namen.join());  // Max,Anna,Tom

// Mit Leerzeichen
console.log(namen.join(' '));  // Max Anna Tom

// Mit Trennzeichen
console.log(namen.join(', '));  // Max, Anna, Tom
console.log(namen.join(' - '));  // Max - Anna - Tom

// Ohne Trenner
console.log(namen.join(''));  // MaxAnnaTom

// Praktisch für URLs
const pfad = ['home', 'user', 'documents'];
console.log(pfad.join('/'));  // home/user/documents

reverse() - Array umkehren

reverse Method
const zahlen = [1, 2, 3, 4, 5];

zahlen.reverse();
console.log(zahlen);  // [5, 4, 3, 2, 1]

// ⚠️ Verändert Original!
// Kopie erst erstellen
const original = [1, 2, 3, 4, 5];
const umgekehrt = original.slice().reverse();
console.log(original);   // [1, 2, 3, 4, 5] (unverändert)
console.log(umgekehrt);  // [5, 4, 3, 2, 1]

sort() - Array sortieren

sort Method
// Strings sortieren
const namen = ['Tom', 'Anna', 'Max', 'Ben'];
namen.sort();
console.log(namen);  // ['Anna', 'Ben', 'Max', 'Tom']

// ⚠️ Zahlen sortieren (VORSICHT!)
const zahlen = [10, 5, 40, 25, 1000];
zahlen.sort();
console.log(zahlen);  // [10, 1000, 25, 40, 5] (als Strings!)

// ✅ RICHTIG: Mit Compare Function
zahlen.sort((a, b) => a - b);
console.log(zahlen);  // [5, 10, 25, 40, 1000]

// Absteigend
zahlen.sort((a, b) => b - a);
console.log(zahlen);  // [1000, 40, 25, 10, 5]

// Objects sortieren
const users = [
    { name: 'Max', age: 25 },
    { name: 'Anna', age: 30 },
    { name: 'Tom', age: 20 }
];

users.sort((a, b) => a.age - b.age);
console.log(users);  // Nach Alter sortiert

forEach() - Über Array iterieren

forEach Method
const namen = ['Max', 'Anna', 'Tom'];

// Jedes Element ausgeben
namen.forEach(name => {
    console.log(name);
});

// Mit Index
namen.forEach((name, index) => {
    console.log(`${index + 1}. ${name}`);
});
// 1. Max
// 2. Anna
// 3. Tom

// Mit Array
namen.forEach((name, index, array) => {
    console.log(`${index}/ ${array.length}: ${name}`);
});

// Praktisch: Array verarbeiten
const zahlen = [1, 2, 3, 4, 5];
let summe = 0;

zahlen.forEach(zahl => {
    summe += zahl;
});

console.log(summe);  // 15

map() - Array transformieren

Erstellt neues Array:

map Method
const zahlen = [1, 2, 3, 4, 5];

// Verdoppeln
const verdoppelt = zahlen.map(zahl => zahl * 2);
console.log(verdoppelt);  // [2, 4, 6, 8, 10]
console.log(zahlen);      // [1, 2, 3, 4, 5] (Original unverändert)

// Namen zu Großbuchstaben
const namen = ['max', 'anna', 'tom'];
const groß = namen.map(name => name.toUpperCase());
console.log(groß);  // ['MAX', 'ANNA', 'TOM']

// Objects transformieren
const users = [
    { firstName: 'Max', lastName: 'Müller' },
    { firstName: 'Anna', lastName: 'Schmidt' }
];

const fullNames = users.map(user => `${user.firstName} ${user.lastName}`);
console.log(fullNames);  // ['Max Müller', 'Anna Schmidt']

// Mit Index
const nummeriert = namen.map((name, index) => `${index + 1}. ${name}`);
console.log(nummeriert);  // ['1. max', '2. anna', '3. tom']

filter() - Array filtern

Erstellt neues Array mit gefilterten Elementen:

filter Method
const zahlen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Nur gerade Zahlen
const gerade = zahlen.filter(zahl => zahl % 2 === 0);
console.log(gerade);  // [2, 4, 6, 8, 10]

// Größer als 5
const groß = zahlen.filter(zahl => zahl > 5);
console.log(groß);  // [6, 7, 8, 9, 10]

// Namen filtern
const namen = ['Max', 'Anna', 'Tom', 'Alexander'];
const kurz = namen.filter(name => name.length <= 4);
console.log(kurz);  // ['Max', 'Anna', 'Tom']

// Objects filtern
const products = [
    { name: 'Laptop', price: 999 },
    { name: 'Mouse', price: 29 },
    { name: 'Keyboard', price: 79 }
];

const günstig = products.filter(p => p.price < 100);
console.log(günstig);  // Mouse, Keyboard

// Leere Strings entfernen
const liste = ['Max', '', 'Anna', '', 'Tom'];
const gefüllt = liste.filter(item => item !== '');
console.log(gefüllt);  // ['Max', 'Anna', 'Tom']

find() - Erstes Element finden

find Method
const zahlen = [1, 2, 3, 4, 5];

// Erstes Element > 3
const gefunden = zahlen.find(zahl => zahl > 3);
console.log(gefunden);  // 4 (erstes Match)

// Wenn nicht gefunden
const result = zahlen.find(zahl => zahl > 10);
console.log(result);  // undefined

// Object finden
const users = [
    { id: 1, name: 'Max' },
    { id: 2, name: 'Anna' },
    { id: 3, name: 'Tom' }
];

const user = users.find(u => u.id === 2);
console.log(user);  // { id: 2, name: 'Anna' }

// Mit findIndex (gibt Index zurück)
const index = users.findIndex(u => u.name === 'Tom');
console.log(index);  // 2

reduce() - Array zu Einzelwert

Akkumulator-Pattern:

reduce Method
const zahlen = [1, 2, 3, 4, 5];

// Summe berechnen
const summe = zahlen.reduce((acc, zahl) => acc + zahl, 0);
console.log(summe);  // 15

// Produkt
const produkt = zahlen.reduce((acc, zahl) => acc * zahl, 1);
console.log(produkt);  // 120

// Maximum finden
const max = zahlen.reduce((acc, zahl) => {
    return zahl > acc ? zahl : acc;
}, zahlen[0]);
console.log(max);  // 5

// Wörter zählen
const wörter = ['Hallo', 'Welt', 'Hallo', 'JavaScript'];
const count = wörter.reduce((acc, wort) => {
    acc[wort] = (acc[wort] || 0) + 1;
    return acc;
}, {});
console.log(count);  // { Hallo: 2, Welt: 1, JavaScript: 1 }

// Preise summieren
const products = [
    { name: 'Laptop', price: 999 },
    { name: 'Mouse', price: 29 },
    { name: 'Keyboard', price: 79 }
];

const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(total);  // 1107

some() & every() - Testen

some & every
const zahlen = [1, 2, 3, 4, 5];

// some - Mindestens ein Element erfüllt Bedingung
const hatGerade = zahlen.some(zahl => zahl % 2 === 0);
console.log(hatGerade);  // true (2, 4 sind gerade)

const hatGroß = zahlen.some(zahl => zahl > 10);
console.log(hatGroß);  // false

// every - ALLE Elemente erfüllen Bedingung
const allePositiv = zahlen.every(zahl => zahl > 0);
console.log(allePositiv);  // true

const alleGerade = zahlen.every(zahl => zahl % 2 === 0);
console.log(alleGerade);  // false

// Praktisch: Validierung
const alter = [18, 25, 30, 22];
const alleVolljährig = alter.every(age => age >= 18);
console.log(alleVolljährig);  // true

Spread Operator - Array erweitern

Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// Arrays kombinieren
const combined = [...arr1, ...arr2];
console.log(combined);  // [1, 2, 3, 4, 5, 6]

// Mit zusätzlichen Werten
const extended = [...arr1, 4, ...arr2, 7];
console.log(extended);  // [1, 2, 3, 4, 4, 5, 6, 7]

// Array kopieren
const kopie = [...arr1];
console.log(kopie);  // [1, 2, 3]

// In Function nutzen
function addieren(...zahlen) {
    return zahlen.reduce((sum, n) => sum + n, 0);
}

console.log(addieren(1, 2, 3, 4));  // 10

// Math.max mit Array
const zahlen = [5, 2, 8, 1, 9];
console.log(Math.max(...zahlen));  // 9

Destructuring - Array entpacken

Array Destructuring
const namen = ['Max', 'Anna', 'Tom'];

// Destructuring
const [erster, zweiter, dritter] = namen;
console.log(erster);   // Max
console.log(zweiter);  // Anna
console.log(dritter);  // Tom

// Rest Operator
const zahlen = [1, 2, 3, 4, 5];
const [first, second, ...rest] = zahlen;
console.log(first);   // 1
console.log(second);  // 2
console.log(rest);    // [3, 4, 5]

// Elemente überspringen
const [a, , c] = namen;
console.log(a);  // Max
console.log(c);  // Tom (Anna übersprungen)

// Default Values
const [x = 1, y = 2, z = 3] = [10];
console.log(x);  // 10
console.log(y);  // 2 (default)
console.log(z);  // 3 (default)

// Swap Values
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);  // 2 1

Praktische Beispiele

Beispiel 1: Duplikate entfernen

Remove Duplicates
const zahlen = [1, 2, 2, 3, 3, 3, 4, 5, 5];

// Mit Set
const unique = [...new Set(zahlen)];
console.log(unique);  // [1, 2, 3, 4, 5]

// Mit filter
const unique2 = zahlen.filter((item, index) => {
    return zahlen.indexOf(item) === index;
});
console.log(unique2);  // [1, 2, 3, 4, 5]

Beispiel 2: Array flach machen

Flatten Array
const nested = [1, [2, 3], [4, [5, 6]]];

// flat() Method
const flat = nested.flat();
console.log(flat);  // [1, 2, 3, 4, [5, 6]]

const flatAll = nested.flat(2);  // Tiefe 2
console.log(flatAll);  // [1, 2, 3, 4, 5, 6]

// Infinite depth
const flatInfinite = nested.flat(Infinity);
console.log(flatInfinite);  // [1, 2, 3, 4, 5, 6]

Beispiel 3: Array chunken

Chunk Array
function chunk(array, size) {
    const chunks = [];
    for (let i = 0; i < array.length; i += size) {
        chunks.push(array.slice(i, i + size));
    }
    return chunks;
}

const zahlen = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(chunk(zahlen, 3));
// [[1, 2, 3], [4, 5, 6], [7, 8]]

Beispiel 4: Shopping Cart

Shopping Cart
const cart = [
    { name: 'Laptop', price: 999, quantity: 1 },
    { name: 'Mouse', price: 29, quantity: 2 },
    { name: 'Keyboard', price: 79, quantity: 1 }
];

// Total Price
const total = cart.reduce((sum, item) => {
    return sum + (item.price * item.quantity);
}, 0);
console.log(`Total: ${total}€`);  // Total: 1136€

// Item names
const names = cart.map(item => item.name);
console.log(names);  // ['Laptop', 'Mouse', 'Keyboard']

// Expensive items
const expensive = cart.filter(item => item.price > 50);
console.log(expensive);  // Laptop, Keyboard

Best Practices

✅ DO:

  1. Immutable Methods bevorzugen (map, filter, slice)
  2. Chaining nutzen (map + filter)
  3. Spread für Kopien statt Mutation
  4. includes() statt indexOf()
  5. find() für Objects
Good Practices
const zahlen = [1, 2, 3, 4, 5];

// ✅ Chaining
const result = zahlen
    .filter(n => n > 2)
    .map(n => n * 2);

// ✅ Spread für Kopie
const kopie = [...zahlen];

// ✅ includes
if (zahlen.includes(3)) { }

// ✅ find für Objects
const users = [{ id: 1 }, { id: 2 }];
const user = users.find(u => u.id === 2);

❌ DON'T:

  1. Nicht Original mutieren (wenn nicht nötig)
  2. Nicht for-Loop für map/filter
  3. Nicht Array[index] für Kopie
Anti-Patterns
// ❌ SCHLECHT: Mutation
const zahlen = [1, 2, 3];
zahlen.push(4);  // Mutiert Original

// ✅ BESSER: Immutable
const zahlen2 = [...zahlen, 4];

// ❌ SCHLECHT: for-Loop statt map
const doubled = [];
for (let i = 0; i < zahlen.length; i++) {
    doubled.push(zahlen[i] * 2);
}

// ✅ BESSER: map
const doubled2 = zahlen.map(n => n * 2);

TipsAndTricks

Tipps & Tricks

Spread Operator für Array-Operationen

Nutze ... für eleganten Code:

// Arrays kombinieren
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];  // [1, 2, 3, 4, 5, 6]

// Array kopieren (shallow)
const copy = [...arr1];

// Element hinzufügen
const newArr = [...arr1, 4];  // [1, 2, 3, 4]

// Math mit Arrays
const zahlen = [5, 2, 8, 1, 9];
Math.max(...zahlen);  // 9

Modern Array Methods chaining

Kombiniere map, filter, reduce für mächtigen Code:

const products = [
    { name: 'Laptop', price: 999, category: 'tech' },
    { name: 'Mouse', price: 29, category: 'tech' },
    { name: 'Desk', price: 299, category: 'furniture' }
];

// Alle tech-Produkte unter 500€, verdoppelt
const result = products
    .filter(p => p.category === 'tech')
    .filter(p => p.price < 500)
    .map(p => p.price * 2);  // [58]

Array Destructuring mit Rest

Extrahiere Werte elegant:

const zahlen = [1, 2, 3, 4, 5];

// Erste paar Elemente
const [first, second] = zahlen;  // 1, 2

// Mit Rest für restliche
const [first, ...rest] = zahlen;  // first=1, rest=[2,3,4,5]

// Elemente überspringen
const [first, , third] = zahlen;  // 1, 3

// Swap Values
let a = 1, b = 2;
[a, b] = [b, a];  // a=2, b=1

find() vs filter() richtig einsetzen

Wähle die passende Methode:

const users = [
    { id: 1, name: 'Max' },
    { id: 2, name: 'Anna' },
    { id: 3, name: 'Tom' }
];

// find() - Erstes Element (oder undefined)
const user = users.find(u => u.id === 2);  // { id: 2, name: 'Anna' }

// filter() - Alle passenden Elemente
const techUsers = users.filter(u => u.name.startsWith('M'));  // [Max]

// Für "gibt es?" nutze some()
const hasAdmin = users.some(u => u.role === 'admin');

📝 Quiz

Was ist der Unterschied zwischen push() und concat()?

📝 Quiz

Wann nutzt man map() statt forEach()?

Übungsaufgaben

Aufgabe 1: Array Basics

Erstelle Array mit Zahlen:

  • Füge Elemente hinzu (push, unshift)
  • Entferne Elemente (pop, shift)
  • Finde Maximum & Minimum

Aufgabe 2: Filtering & Mapping

Gegeben: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  • Filtere nur gerade Zahlen
  • Verdopple alle Zahlen
  • Berechne Summe

Aufgabe 3: Objects Array

Erstelle Array mit User-Objects:

  • Filtere nach Alter
  • Mappe zu Namen-Array
  • Finde User by ID

Aufgabe 4: Advanced

  • Duplikate entfernen
  • Array sortieren
  • Flatten nested Array

Nächste Schritte

Du kennst jetzt:

  • ✅ Array Basics & Zugriff
  • ✅ Add/Remove Methods (push, pop, shift, unshift)
  • ✅ Higher-Order Methods (map, filter, reduce)
  • ✅ find, some, every
  • ✅ Spread & Destructuring
  • ✅ sort, reverse, slice, splice
  • ✅ Best Practices

Als Nächstes lernst du:

  • Objects im Detail
  • Object Methods
  • Object Destructuring
  • JSON

Weiter so! 🚀

JavaScriptLektion 9 von 17
53% abgeschlossen
Lektion abgeschlossen!

Gut gemacht! 🎉

Du hast "JavaScript Arrays - Listen & Array Methods" abgeschlossen

Artikel bewerten

0.0 (0 Bewertungen)

Bitte einloggen um zu bewerten