• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Remove duplicate items from an array

Remove duplicate items from an array

Remove duplicate items from an array

Let’s imagine you had an array of sandwiches, and some of the items in it were listed more than once.

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

You want to get an updated list with the duplicates removed, a process called deduplication.

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

Helper function:

/*!
 * Remove duplicate items from an array
 * (c) 2021 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));
}

Source

https://vanillajstoolkit.com/helpers/dedupe/

Miscellaneous

Related Snippets:

  • Finding a specific object in an array of objects
  • Remove Duplicates From an Array
  • Find a Specific Element from an Array
  • Get and set the text of an element (without markup)

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us