Skip to main content

JavaScript: How to Filter Duplicate Items in Array

The most straightforward method for that is the JavaScript Set method.

Remember that math subject about Venn diagram?

In it, the Set cannot have duplicates. Like the word "BOB". The set from the word will be {B, O}, and not {B, O, B}.

The similar concept in JavaScript Set.

This Set direct filtering works only for String and Number items from an Array.


Input Array

For example, we have these:


Filtering Duplicates Using Set Method

Then the straightforward method to filter the duplicates can be done like so:

The new Array from that will consist of unique item.


Helper Function

Let's wrap that method into a helper function:

Or, using arrow function syntax:


Usage

Then we can use that helper function:


How About Input Object item type?

We can first try transform that with JSON.stringify to make the Object as String, then we can use those transformed items. Then we use JSON.parse to revert it back.

Let's try that:

Please be careful if the object is large using the function above. We need to make sure our input will not be "some wonky giants".

Anyway, we can use map approach first to avoid creating full new Set to make it more efficient. But I won't show it here because that's too specific edge-case, and it depends on what case.

And keep in mind, JSON.stringify for this kind of input { theKey: undefined } will completely omit theKey.

And of course, if there's Function in the array, it will also be "trimmed" by the JSON.stringify.

Filtering tomatoes

Reference

  • Set documentation at MDN
  • Spread operator (the triple dots ...) documentation at MDN
    The spread operator in a = [...otherArray] creates a new array by copying elements from otherArray, ensuring a shallow copy without modifying the original.
Last modified on

Comments