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));

Join the Lean Web Club! Coaching. Courses. Coding resources. Get the skills, confidence, and support you need to learn front-end web development and achieve long-term success.


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