Flatten a nested array to a given depth and flatten a nested object into dot paths.
Array flatten
Like Array.prototype.flat(depth): walk the array and, for each element that is an array, recurse with depth - 1 while depth remains. Recursion is clear; an explicit stack avoids call-stack limits for very deep input. flat also skips holes in sparse arrays.
Object flatten
Turn { user: { address: { city: 'Pune' } } } into { 'user.address.city': 'Pune' }. Useful for form libraries, query strings, analytics payloads, translation keys and diffing. Decide how to treat arrays (index paths such as tags.0) and empty objects. The inverse, unflatten, splits each path and builds nested objects.
function flatten(arr, depth = 1) {
const out = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) out.push(...flatten(item, depth - 1));
else out.push(item);
}
return out;
}
// Iterative, unlimited depth, no recursion limit
function flattenDeep(arr) {
const stack = [...arr];
const out = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) stack.push(...item);
else out.push(item);
}
return out.reverse();
}
function flattenObject(obj, prefix = '', out = {}) {
for (const [key, value] of Object.entries(obj)) {
const path = prefix ? `${prefix}.${key}` : key;
if (value && typeof value === 'object' && !(value instanceof Date) && Object.keys(value).length) {
flattenObject(value, path, out);
} else {
out[path] = value;
}
}
return out;
}
function unflattenObject(flat) {
const result = {};
for (const [path, value] of Object.entries(flat)) {
const keys = path.split('.');
let node = result;
keys.forEach((key, i) => {
if (i === keys.length - 1) node[key] = value;
else node = node[key] ??= /^\d+$/.test(keys[i + 1]) ? [] : {};
});
}
return result;
}
// Demo
const nested = [1, [2, [3, [4, [5]]]]];
assert.deepEqual(flatten(nested), [1, 2, [3, [4, [5]]]]);
assert.deepEqual(flatten(nested, 2), [1, 2, 3, [4, [5]]]);
assert.deepEqual(flatten(nested, Infinity), nested.flat(Infinity));
assert.deepEqual(flattenDeep(nested), [1, 2, 3, 4, 5]);
const profile = { user: { name: 'Asha', address: { city: 'Pune' }, tags: ['js', 'vue'] }, active: true };
const flat = flattenObject(profile);
assert.deepEqual(flat, { 'user.name': 'Asha', 'user.address.city': 'Pune', 'user.tags.0': 'js', 'user.tags.1': 'vue', active: true });
assert.deepEqual(unflattenObject(flat), profile);
console.log(flat);Example
A related one-liner question is safely reading a nested path, like lodash get:
const get = (obj, path, fallback) =>
path.replace(/\[(\d+)\]/g, '.$1').split('.').reduce((node, key) => node?.[key], obj) ?? fallback;
assert.equal(get({ a: { b: [{ c: 3 }] } }, 'a.b[0].c'), 3);
assert.equal(get({ a: {} }, 'a.x.y', 'none'), 'none');Optional chaining (?.) inside the reducer stops at the first missing level instead of throwing.
Follow-up questions interviewers ask
Try answering each one before you open it.
What are the complexities?
Both flatten functions are O(n) in the total number of elements or leaf values visited. Using out.push(...items) with huge arrays can exceed the argument limit; push items one by one or use the iterative version for very large inputs.