Languages
[Edit]
EN

JavaScript - remove duplicates from array

15 points
Created by:
AnnLen
11260

In this short article, we would like to show how to remove duplicated items in an array in JavaScript.

Quick solution:

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

Iterative example

This approach is useful when we want to reduce the number of iterations.

// ONLINE-RUNNER:browser;

const removeDuplicates = (array) => {
  	const result = [];
	const blocker = {}; // prevents against item duplication
  	for (const item of array) {
    	if (blocker.hasOwnProperty(item)) {
        	continue;
        }
      	blocker[item] = true;
      	result.push(item);
    }
  	return result;
};

// Usage example:

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

console.log(JSON.stringify(uniqueItems)); // [1,2,3]
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