Lodash uniqBy: Filter Unique Objects by Property

Managing duplicate data in JavaScript arrays is a common challenge, especially when dealing with collections of objects representing database records or API responses. This article explains how the Lodash utility library's _.uniqBy method operates, detailing how it evaluates object uniqueness through property keys or custom iteratee functions, keeps the first occurrence of each unique value, and returns a deduplicated array without mutating the original data.

Understanding _.uniqBy

The _.uniqBy method creates a duplicate-free version of an array. Unlike standard deduplication methods that compare primitive values or object references directly (such as new Set(array) or Lodash's _.uniq), _.uniqBy accepts an "iteratee." This iteratee defines the criteria used to compute the uniqueness of each item in the array.

The syntax for the method is:

_.uniqBy(array, [iteratee=_.identity])

Filtering by Property Name (String Shorthand)

The most common use case for _.uniqBy is filtering an array of objects based on a specific key, such as an id or code. You provide the property name as a string for the iteratee parameter:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice Duplicate' },
  { id: 3, name: 'Charlie' }
];

const uniqueUsers = _.uniqBy(users, 'id');

console.log(uniqueUsers);
// Output:
// [
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Bob' },
//   { id: 3, name: 'Charlie' }
// ]

When iterating through users, _.uniqBy extracts the value of id for each object. It stores the generated keys internally and preserves only the first object encountered with that key. The object { id: 1, name: 'Alice Duplicate' } is omitted because an item with id: 1 was already processed.

Filtering with a Custom Function

When uniqueness depends on computed logic, transformations, or nested properties, you can pass a function as the iteratee:

const measurements = [
  { value: 4.2, unit: 'px' },
  { value: 4.8, unit: 'px' },
  { value: 5.1, unit: 'px' }
];

// Deduplicate based on the floored value
const uniqueMeasurements = _.uniqBy(measurements, (item) => Math.floor(item.value));

console.log(uniqueMeasurements);
// Output:
// [
//   { value: 4.2, unit: 'px' },
//   { value: 5.1, unit: 'px' }
// ]

You can also combine multiple properties to establish compound uniqueness:

const products = [
  { category: 'shoes', size: 10 },
  { category: 'shoes', size: 11 },
  { category: 'shoes', size: 10 }
];

const uniqueProducts = _.uniqBy(products, (p) => `${p.category}-${p.size}`);

console.log(uniqueProducts);
// Output:
// [
//   { category: 'shoes', size: 10 },
//   { category: 'shoes', size: 11 }
// ]

Key Behaviors of _.uniqBy