❌Remove array duplicates with Set

Using Set

This is O(n). The common arr.filter((x, i) => arr.indexOf(x) === i) trick is O(n²), because indexOf searches the array again for every item.

const array = ['🐑', 1, 2, '🐑', '🐑', 3]

// Step 1
const uniqueSet = new Set(array)
// Set { '🐑', 1, 2, 3 }

// Step 2
const backToArray = [...uniqueSet]
// ['🐑', 1, 2, 3]

// or Step 1
const uniqueSet = [...new Set(array)]
// ['🐑', 1, 2, 3]

Keyboard shortcuts

Tap these keys to navigate to the appropriate page.