How Lodash Concat Handles Deeply Nested Arrays
The Lodash _.concat method merges values and arrays into
a new consolidated array, but it only performs a shallow, single-level
concatenation. When handling heavily deeply nested arrays,
_.concat does not automatically unpack deep layers,
preserving instead the internal nested structures intact. This article
breaks down the exact mechanics of _.concat on
multi-dimensional arrays, explains why internal structures are retained,
and demonstrates how to achieve deep recursive flattening using
complementary Lodash functions.
The Shallow Nature of
_.concat
By design, _.concat mirrors the behavior of JavaScript's
native Array.prototype.concat, with the added benefit of
handling non-array inputs cleanly. It unwraps only the top-level array
arguments provided to the function. Any sub-arrays residing inside those
elements are treated as literal values rather than collections to be
unpacked.
Consider the following example with multi-level nesting:
const _ = require('lodash');
const base = [1, [2]];
const nested = [[[3]], [[[[4]]]]];
const result = _.concat(base, nested, 5);
// Output: [1, [2], [[3]], [[[[4]]]], 5]In this execution:
- The top-level wrapper around
nestedis stripped. - The immediate children (
[[3]]and[[[[4]]]]) are appended to the root array without recursive inspection. - The internal arrays retain their respective nesting depths of 2 and 4.
Why _.concat
Does Not Deeply Flatten
_.concat prioritizes performance, predictability, and
structural integrity. Automatically flattening arrays recursively is
computationally expensive and can destroy intended data structures (such
as matrices, trees, or multi-dimensional coordinate pairs).
Consequently, _.concat adheres strictly to depth-1
merging.
Resolving and Flattening Deeply Nested Arrays
If the goal is to merge arrays and resolve all nested levels into a
single, flat array, _.concat must be paired with flattening
utilities. Lodash provides dedicated methods for this purpose:
1. Complete Flattening
with _.flattenDeep
To strip all nested dimensions completely after merging, wrap
_.concat inside _.flattenDeep:
const array1 = [1, [2, [3]]];
const array2 = [[[[4]]], 5];
const fullyFlattened = _.flattenDeep(_.concat(array1, array2));
// Output: [1, 2, 3, 4, 5]2. Controlled
Depth Flattening with _.flattenDepth
If a specific level of nesting needs to be preserved, use
_.flattenDepth by providing an explicit depth
parameter:
const data1 = [1, [2, [3]]];
const data2 = [[[4]]];
// Flattens up to 2 levels deep
const partiallyFlattened = _.flattenDepth(_.concat(data1, data2), 2);
// Output: [1, 2, 3, [4]]Summary
Lodash's _.concat resolves deeply nested arrays by
flattening only the outermost container and preserving all deeper child
structures. To merge deeply nested collections into a flat list,
_.concat should be combined with _.flattenDeep
or _.flattenDepth.