Sobes.tech
Junior

Wie kann man alle Duplikate aus einem Array entfernen?

sobes.tech KI

Antwort von AI

Es gibt mehrere gängige Methoden:

  1. Verwendung von Set: Die modernste und prägnanteste Methode. Set speichert nur eindeutige Werte.

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArr = [...new Set(arr)];
    // uniqueArr wird [1, 2, 3, 4, 5]
    
    const arr = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }, { id: 1, name: 'A' }];
    const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
    // Für Objekte muss man sie in Strings umwandeln, um sie im Set korrekt zu vergleichen
    // uniqueArr wird [{ id: 1, name: 'A' }, { id: 2, name: 'B' }]
    
  2. Verwendung von filter und indexOf: Filtern des Arrays, wobei nur Elemente verbleiben, deren erstes Vorkommen mit dem aktuellen Index übereinstimmt.

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
    // uniqueArr wird [1, 2, 3, 4, 5]
    
  3. Verwendung von reduce: Erstellen eines neuen Arrays, indem Elemente hinzugefügt werden, wenn sie noch nicht im Akkumulator sind.

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArr = arr.reduce((accumulator, current) => {
        if (!accumulator.includes(current)) {
            accumulator.push(current);
        }
        return accumulator;
    }, []);
    // uniqueArr wird [1, 2, 3, 4, 5]
    
    const arr = [1, 2, 2, 3, 4, 4, 5];
    const uniqueArr = arr.reduce((accumulator, current) => accumulator.includes(current) ? accumulator : [...accumulator, current], []);
    // Kürzere Variante
    // uniqueArr wird [1, 2, 3, 4, 5]
    
  4. Verwendung von Objekt/Map: Erstellen eines temporären Objekts oder Map, um bereits gesehene Elemente zu verfolgen.

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const seen = {};
    const uniqueArr = arr.filter(item => seen.hasOwnProperty(item) ? false : (seen[item] = true));
    // uniqueArr wird [1, 2, 3, 4, 5]
    
    const arr = [1, 2, 2, 3, 4, 4, 5];
    const seen = new Map();
    const uniqueArr = arr.filter(item => {
        if (!seen.has(item)) {
            seen.set(item, true);
            return true;
        }
        return false;
    });
    // uniqueArr wird [1, 2, 3, 4, 5]
    

Die Methode mit Set ist in der Regel die effizienteste und lesbarste für primitive Typen. Für Objekte kann zusätzliche Logik erforderlich sein.