Remove duplicates from a array of objects JavaScript

Removing duplicates from an array of objects is a common task in JavaScript. We need to identify objects with the same properties and values, keeping only unique objects in the result.

Using JSON.stringify() with Map

The most straightforward approach uses JSON.stringify() to convert objects to strings for comparison:

const arr = [
    {
        "timestamp": 564328370007,
        "message": "It will rain today"
    },
    {
        "timestamp": 164328302520,
        "message": "will it rain today"
    },
    {
        "timestamp": 564328370007,
        "message": "It will rain today"
    },
    {
        "timestamp": 564328370007,
        "message": "It will rain today"
    }
];

const map = {};
const newArray = [];
arr.forEach(el => {
    if (!map[JSON.stringify(el)]) {
        map[JSON.stringify(el)] = true;
        newArray.push(el);
    }
});

console.log(newArray);
[
  { timestamp: 564328370007, message: 'It will rain today' },
  { timestamp: 164328302520, message: 'will it rain today' }
]

Using filter() with findIndex()

A more functional approach uses filter() with findIndex() to keep only the first occurrence of each unique object:

const arr = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
    { id: 1, name: "John" },
    { id: 3, name: "Bob" }
];

const uniqueArray = arr.filter((obj, index) => 
    arr.findIndex(item => JSON.stringify(item) === JSON.stringify(obj)) === index
);

console.log(uniqueArray);
[
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
]

Using Set with JSON.stringify()

A concise solution using Set to track seen objects:

const arr = [
    { category: "fruit", name: "apple" },
    { category: "vegetable", name: "carrot" },
    { category: "fruit", name: "apple" }
];

const seen = new Set();
const unique = arr.filter(obj => {
    const key = JSON.stringify(obj);
    if (seen.has(key)) {
        return false;
    }
    seen.add(key);
    return true;
});

console.log(unique);
[
  { category: 'fruit', name: 'apple' },
  { category: 'vegetable', name: 'carrot' }
]

Comparison

Method Performance Readability Memory Usage
Map with forEach Fast Good Moderate
filter + findIndex Slow (O(n²)) Excellent Low
Set approach Fast Very Good Moderate

Key Considerations

Property Order: JSON.stringify() maintains property order, so objects with different property orders will be considered different.

Performance: For large arrays, the Map and Set approaches are more efficient than filter + findIndex.

Conclusion

Use the Map approach for best performance, or the Set method for cleaner code. The filter + findIndex approach works well for smaller datasets where readability is prioritized.

Updated on: 2026-03-15T23:18:59+05:30

717 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements