Lodash _.union vs _.concat: Key Differences Explained

This article explores the fundamental distinctions between the _.union and _.concat methods provided by the Lodash JavaScript utility library. While both functions allow developers to combine multiple data sets into a single array, their core behaviors diverge sharply when handling duplicate items and argument types. Understanding these differences ensures you select the right method for array manipulation, memory efficiency, and data integrity.

1. Duplicate Handling (Uniqueness)

The most defining difference between the two methods is deduplication:

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];

_.union(array1, array2);
// Output: [1, 2, 3, 4]

_.concat(array1, array2);
// Output: [1, 2, 3, 2, 3, 4]

2. Argument Types and Flattening

The methods differ in how they process non-array values:

// Passing individual values alongside arrays:
_.union([1, 2], 3, 4);
// Output: [1, 2] (non-array arguments are ignored)

_.concat([1, 2], 3, 4);
// Output: [1, 2, 3, 4]

3. Performance Overhead

Because _.union enforces element uniqueness, it must track previously seen values internally. This requires extra computational cycles and memory allocations compared to _.concat.

_.concat simply shallow-copies items into a new array buffer, making it significantly faster for large data sets when uniqueness is not required or when the input data is already known to contain distinct elements.

Summary of Use Cases