Flattening arrays
suggest changeOne level of nesting
Use flat() with its default depth of 1 to flatten one nesting level:
const values = [1, 2, [3, 4]];
console.log(values.flat()); // [1, 2, 3, 4]
flatMap() combines mapping and flattening one level:
const words = ['modern JavaScript', 'array methods'];
const tokens = words.flatMap(word => word.split(' '));
console.log(tokens); // ['modern', 'JavaScript', 'array', 'methods']
Deeper nesting
Pass the required depth to flat():
const deeplyNested = [4, [5, 6, [7, 8], 9]];
console.log(deeplyNested.flat(2)); // [4, 5, 6, 7, 8, 9]
Pass Infinity only when every nesting level should be removed: values.flat(Infinity). Flattening returns a new array and removes empty slots at the levels it processes; it does not mutate the source array.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents