DE
JavaScript - Entfernen von Duplikaten aus einem Array
3
points
In diesem kurzen Artikel wird gezeigt, wie doppelte Elemente in einem Array in JavaScript entfernt werden können.
Die schnelle Lösung:
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
const result = array.filter((item, index, array) => array.indexOf(item) === index);
console.log(JSON.stringify(result)); // [1,2,3]
Iteratives Beispiel
Dieser Lösungsweg ist nützlich, wenn wir die Iterationenanzahl reduzieren wollen.
// ONLINE-RUNNER:browser;
const removeDuplicates = (array) => {
const result = [];
const blocker = {}; // Es schützt vor der Duplizierung von Elementen
for (const item of array) {
if (blocker.hasOwnProperty(item)) {
continue;
}
blocker[item] = true;
result.push(item);
}
return result;
};
// Verwendungsbeispiel:
const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
const uniqueItems = removeDuplicates(array);
console.log(JSON.stringify(uniqueItems)); // [1,2,3]