Skip to main content Accessibility Feedback

dedupe.js

Remove duplicate items from an array.

Source Code

Example

let sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];

// returns ["turkey","ham","tuna","pb&j"]
let deduped = dedupe(sandwiches);

The helper function

/**
 * Remove duplicate items from an array
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Array} arr The array
 * @return {Array}     A new array with duplicates removed
 */
function dedupe (arr) {
	return Array.from(new Set(arr));
}

How it works

The new Set() constructor creates an iterable collection of items, just like an array. But, each item can only be included once.

To remove any duplicates, we can pass our array into the new Set() constructor, then convert the returned collection back into an array.

let deduped = Array.from(new Set(sandwiches));

Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.


Find this useful? You can support my work by purchasing an annual membership.