Languages
[Edit]
EN

JavaScript - remove duplicates from array

15 points
Created by:
DEX7RA
520

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]

 

Reusable function example

The below approaches reduce the number of iterations.

1. Set based approach

// ONLINE-RUNNER:browser;

const removeDuplicates = (array) => {
  	const result = [];
	const blocker = new Set(); // prevents against item duplication
  	for (const item of array) {
    	if (blocker.has(item)) {
            continue;
        }
        blocker.add(item);
        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]

 

2. Simple types approach

This solution should be used when each item has the same type in the array, and the type is one of: boolean, number or string.

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

 

References

Alternative titles

  1. JavaScript - get all unique values in array
  2. JavaScript - get array of unique values from array containing duplicates
  3. JavaScript - get all distinct values in array
  4. JavaScript - delete duplicate elements from array
  5. JavaScript - filter array to have unique values
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