Sobes.tech
Middle+

Implement a function to filter duplicates from an array. Why is Set not suitable for objects?

sobes.tech AI

Answer from AI

To filter duplicates from an array, you can use the Set object, which stores only unique values. However, Set is not suitable for objects because it compares objects by reference, not by content. That is, two different objects with the same fields will be considered different elements.

Example of a duplicate filtering function for primitive values:

function uniqueArray(arr) {
  return [...new Set(arr)];
}

For objects, you need to implement comparison by content, for example, using JSON serialization or deep comparison:

function uniqueObjects(arr) {
  const seen = new Set();
  return arr.filter(item => {
    const serialized = JSON.stringify(item);
    if (seen.has(serialized)) {
      return false;
    } else {
      seen.add(serialized);
      return true;
    }
  });
}

This method works if the order of keys and data types in objects are stable. For more complex cases, deep comparison or specialized libraries are used.