Back to library
📜JavaScriptjavascriptbeginner

Remove Duplicates from Array

Get unique values from an array using multiple methods

arraysutilities

Code

1// Method 1: Using Set (simplest)
2const unique = (arr) => [...new Set(arr)];
3
4// Method 2: Using filter
5const uniqueFilter = (arr) => {
6  return arr.filter((value, index, self) => {
7    return self.indexOf(value) === index;
8  });
9};
10
11// Method 3: For array of objects
12const uniqueBy = (arr, key) => {
13  return [...new Map(arr.map(item => [item[key], item])).values()];
14};
15
16// Usage examples
17const numbers = [1, 2, 2, 3, 4, 4, 5];
18console.log(unique(numbers)); // [1, 2, 3, 4, 5]
19
20const users = [
21  { id: 1, name: 'John' },
22  { id: 2, name: 'Jane' },
23  { id: 1, name: 'John' }
24];
25console.log(uniqueBy(users, 'id')); // [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}]

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.