TypeScript: Keep One Object per Unique Property Value
The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.
This article explains how to transform an array of objects in TypeScript so that you keep only one object for each unique value of a given property. You will learn several practical approaches, from simple loops to using Map and reduce, with code examples and guidance on choosing the right method for your data.
Formula
The core idea is to use a Map (or a plain object) where the keys are the property values and the values are the objects themselves. For each object in the array, check if the key already exists; if not, add it. This gives you the first occurrence for each unique value.
In pseudocode: result = [], seen = new Map(). For each obj in arr, let k = obj[key]. If seen.has(k) is false, set seen.set(k, true) and push obj to result.
Worked Example
Using the default input: [{"id":1,"name":"a"},{"id":2,"name":"a"},{"id":3,"name":"b"}] and key "name".
- Initialize result = [], seen = new Map().
- First object: key = “a”, not in seen, so add it: result = [{id:1,name:”a”}], seen has “a”.
- Second object: key = “a”, already seen, skip.
- Third object: key = “b”, not seen, add: result = [{id:1,name:”a”}, {id:3,name:”b”}].
Final result: [{"id":1,"name":"a"},{"id":3,"name":"b"}].
Why You Might Need This
When working with data from APIs, CSV files, or user input, you often encounter duplicate records. For example, a list of products might have multiple entries for the same product ID, or a list of users might contain repeated email addresses. Keeping only one object per unique property value is a common data-cleaning step, essential for accurate counts, display, or further processing.
Method 1: Using a Map (Recommended)
The most efficient and type-safe way in TypeScript is to use a Map. It preserves insertion order and works with any value type (strings, numbers, even objects as keys, though you usually use primitives).
function uniqueBy<T>(arr: T[], key: keyof T): T[] {
const seen = new Map<T[keyof T], boolean>();
return arr.filter(obj => {
const val = obj[key];
if (seen.has(val)) return false;
seen.set(val, true);
return true;
});
}
// Usage
const data = [{id:1,name:"a"},{id:2,name:"a"},{id:3,name:"b"}];
const unique = uniqueBy(data, "name");
// unique: [{id:1,name:"a"},{id:3,name:"b"}]
This method is concise, fast (O(n)), and works with any property name. The filter with a closure ensures you only keep the first occurrence.
Method 2: Using Reduce
If you prefer functional programming, reduce is another option. It builds an accumulator array while tracking seen keys.
function uniqueByReduce<T>(arr: T[], key: keyof T): T[] {
const seen = new Set<T[keyof T]>();
return arr.reduce<T[]>((acc, obj) => {
const val = obj[key];
if (!seen.has(val)) {
seen.add(val);
acc.push(obj);
}
return acc;
}, []);
}
This is functionally equivalent to the Map version, but uses a Set for tracking. Both are clear, but the filter version is often more readable.
Method 3: Using a Plain Object (with Caution)
Before Map was common, developers used plain objects as dictionaries. However, this has pitfalls: properties like "__proto__" or "constructor" can cause bugs, and keys are always converted to strings. For most cases, prefer Map or Set.
// Not recommended, but shown for completeness
function uniqueByObject<T>(arr: T[], key: keyof T): T[] {
const seen: Record<string, boolean> = {};
return arr.filter(obj => {
const val = String(obj[key]);
if (seen[val]) return false;
seen[val] = true;
return true;
});
}
This works for simple cases, but the string conversion can lead to unexpected collisions (e.g., number 1 and string “1” are treated as the same).
How to Choose the Right Method
- Use Map/Set when you need type safety, handle any primitive values, or want to preserve the original object references.
- Use plain object only if you are certain the keys are safe strings and you don’t care about type distinctions.
- Consider the size – all methods are O(n), but Map has slightly more overhead than a plain object, though it’s negligible for typical datasets.
- If you need the last occurrence instead of the first, you can either reverse the array first or use a different approach (e.g., build a map from key to object, then take values).
Common Mistakes and Edge Cases
- Using a property that doesn’t exist – all objects will have
undefinedas the key, so only the first object is kept. Ensure the property exists. - Case sensitivity – “Apple” and “apple” are different. If you want case-insensitive, normalize the key (e.g.,
val.toLowerCase()). - Nested properties – the key must be a direct property. For nested, you need a custom function to extract the value.
- Objects with same key but different values – you keep the first one. If you need to merge or choose based on other criteria, you need a more complex logic.
Frequently Asked Questions
Does this work with arrays of objects from JSON?
Yes, as long as the objects are plain objects (not class instances) and the property you use is a primitive (string, number, boolean). The methods above work on any array of objects.
How do I keep the last occurrence instead of the first?
You can reverse the array before applying the filter, or build a Map from key to object (overwriting) and then extract the values. The latter is more efficient: const map = new Map(arr.map(obj => [obj[key], obj])); const result = Array.from(map.values());
What if the property value is an object or array?
Using objects as keys in a Map works by reference, not by deep equality. Two different objects with the same content will be considered different. For deep equality, you need to serialize the value (e.g., JSON.stringify) or use a library, but that is slower.
Can I use this with TypeScript generics to preserve types?
Yes, the examples above use generics (<T>) to preserve the object type. The key parameter is typed as keyof T to ensure the property exists.
Is there a built-in method in TypeScript for this?
No, TypeScript does not have a built-in unique-by-property method. You have to implement it yourself, but the Map/filter approach is standard and recommended.
What about performance for very large arrays?
All methods are O(n), but using a Map or Set is generally faster than using a plain object for large datasets because it avoids string conversion. Memory usage is similar.
Related
Formula used
in arr | Input array (JSON) | - | [{"id":1,"name":"a"},{"id":2,"name":"a"},{"id":3,"name":"b"}] | 0
in key | Property key | - | name | 0
out result | Unique objects | - | dedupe(arr,key) | 0Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.