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:
_.union: Creates an array of unique values in order, from all given arrays. It treats the inputs as mathematical sets, comparing elements using theSameValueZeroequality algorithm. If an element appears multiple times across the input arrays, only its first occurrence is included in the output._.concat: Merges arrays and values sequentially without checking for uniqueness. All elements are preserved exactly as they appear, including duplicates.
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:
_.union: Designed exclusively to operate on arrays. Any argument passed to_.unionthat is not an array (such as primitive numbers, strings, or plain objects) is ignored or will not be parsed as distinct elements._.concat: Accepts both arrays and individual values as arguments. It flattens array arguments by one level while appending primitive values or objects directly into the resulting array.
// 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
- Use
_.unionwhen you need to merge multiple arrays into a single collection of distinct elements and want to eliminate duplicates automatically. - Use
_.concatwhen you need to quickly combine arrays or append individual elements together while preserving the original frequency and order of all values.