Languages
[Edit]
PL

JavaScript - usuwanie zduplikowanych elementów z tablicy

8 points
Created by:
Adnaan-Robin
664

W tym krótkim artykule chcielibyśmy pokazać jak w prosty sposób można usuwać zduplikowane elementy z tablicy w języku JavaScript.

Szybkie rozwiązanie:

// 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]

 

Iteracyjne podejście

To podejście jest dobre, gdy chcemy zredukować ilość niepotrzebnych iteracji.

// ONLINE-RUNNER:browser;

const removeDuplicates = (array) => {
  	const result = [];
	const blocker = {}; // chroni nas przed duplikacją elementów tablicy
  	for (const item of array) {
    	if (blocker.hasOwnProperty(item)) { // jeśli element wystąpił już to ignorujemy go
        	continue;
        }
      	blocker[item] = true;
      	result.push(item);
    }
  	return result;
};

// Przykład użycia:

const array = [1, 2, 3, 1, 1, 2, 2, 3, 3];
const uniqueItems = removeDuplicates(array);

console.log(JSON.stringify(uniqueItems)); // [1,2,3]

References

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