Languages
[Edit]
DE

JavaScript - Entfernen von Duplikaten aus einem Array

3 points
Created by:
Nikki
10520

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]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join