Remove Duplicate Elements From An Array While Preserving Order In Ruby
Deduplicate an array in insertion order using Array#uniq.
Description
Array#uniq removes duplicate elements while preserving the order of first occurrence. Passing a block lets you deduplicate by a computed attribute — useful for removing duplicate records by ID, objects by slug, or hashes by a specific key. uniq! mutates in place and returns nil if no duplicates were found, making the non-bang version safer for most contexts.
Sample input:
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
Sample Output:
[3, 1, 4, 5, 9, 2, 6]
Answer
# Basic dedup — preserves first-occurrence order
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
items.uniq
# => [3, 1, 4, 5, 9, 2, 6]
# Dedup by attribute (objects or hashes)
records = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 1, name: "Alice (duplicate)" }
]
records.uniq { |r| r[:id] }
# => [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}]
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀