JavaScript
Array Flattening
Flatten a multi-dimensional array into one dimension.
By EZ4Code Team
arrayflatten
Code
function flatten(arr, depth = Infinity) {
return arr.reduce((acc, val) =>
Array.isArray(val) && depth > 0
? acc.concat(flatten(val, depth - 1))
: acc.concat(val),
[]
);
}
// Using native flat
const flat = arr => arr.flat(Infinity);Explanation
Recursively flattens or uses the native flat method for arbitrary depth.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.