EN/CH Mode
BRUCE_FE JS Interview Notes - Flatten Array or Object Implementation
Learn how to implement flattening of arrays and objects, master recursive and iterative processing methods, and enhance frontend interview competitiveness.
EN/CH Mode
Lazy to read articles? Then watch videos!
What is Array/Object Flattening?
Flattening is the process of converting multi-level nested data structures into single-level structures. In frontend development, it's commonly used when processing nested JSON data returned from APIs or handling complex tree structures.
- 1. Array flattening: Convert multi-dimensional arrays to one-dimensional arrays
- 2. Object flattening: Convert nested objects to single-level key-value pairs
These types of questions test understanding of recursion, iteration, and how to handle complex data structures.
1. Implement Array Flattening
Array flattening can be implemented through recursive or iterative methods. In interviews, you're usually required to hand-write the implementation rather than directly using Array.flat()
ใ
Method 1: Recursive Approach
function flattenArray(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
// Merge recursive results into current array
result = result.concat(flattenArray(item));
} else {
result.push(item);
}
});
return result;
}
// Example
const nestedArray = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(nestedArray)); // [1, 2, 3, 4, 5, 6]
2. Implement Object Flattening
Object flattening converts nested objects to single-level objects, typically using dot notation to represent levels.
function flattenObject(obj, prefix = '') {
let result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
// Nested object, recursive processing
Object.assign(result, flattenObject(obj[key], newKey));
} else {
// Primitive values or arrays, direct assignment
result[newKey] = obj[key];
}
}
}
return result;
}
// Example
const nestedObject = {
a: 1,
b: {
c: 2,
d: {
e: 3
}
},
f: 4
};
console.log(flattenObject(nestedObject));
/*
Output:
{
'a': 1,
'b.c': 2,
'b.d.e': 3,
'f': 4
}
*/