Lesson 81 of 296
Flatten an array, and curry
On this page
Task 1: flatten
"Write flatten(arr, depth) that flattens nested arrays to the given depth, without using Array.prototype.flat."
Questions to ask first
- "What should the default depth be?" (The built-in uses 1.)
- "Can the nesting be very deep?" (If yes, recursion may overflow the stack, so an iterative version is safer.)
Recursive solution
function flatten(arr, depth = 1) {
const result = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}- If the item is an array and we are still allowed to go deeper, flatten it with
depth - 1and add its items. - Otherwise add the item as it is.
flatten([1, [2, [3, [4]]]]) [1, 2, [3, [4]]]
flatten([1, [2, [3, [4]]]], Infinity) [1, 2, 3, 4]
flatten([1, [2]], 0) [1, [2]]Iterative solution (full flatten, no recursion)
Uses a stack (Part 10) instead of the call stack, so very deep nesting cannot cause a stack overflow:
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse();
}We take items from the end (pop is fast), so the result is built backwards and reversed at the end.
Cost
O(n) time, where n is the total number of items at all levels.
Task 2: curry
"Write curry(fn) so a function with several arguments can be called with them one at a time, or in groups."
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
curriedAdd(1)(2)(3) 6
curriedAdd(1, 2)(3) 6
curriedAdd(1)(2, 3) 6
curriedAdd(1, 2, 3) 6What currying is
Currying turns a function that takes several arguments into a chain of functions that take them bit by bit. It is useful for building specialised functions from general ones:
const multiply = curry((a, b) => a * b);
const double = multiply(2);
double(5); 10The key fact: fn.length
A function's length property is the number of parameters it declares. add.length is 3. (Rest parameters and parameters with default values are not counted.)
The solution
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return (...more) => curried.apply(this, [...args, ...more]);
};
}- If we have collected enough arguments, call the original.
- Otherwise return a new function that remembers the arguments so far (a closure) and waits for more.
Variation: infinite currying
"Make sum(1)(2)(3)() return 6. An empty call ends the chain."
function sum(a) {
return function next(b) {
if (b === undefined) return a;
return sum(a + b);
};
}
sum(1)(2)(3)(); 6Follow-up questions
- "What happens with rest parameters or default values?"
fn.lengthdoes not count them, so curry may call the function too early. A solution is to pass the arity (number of arguments) explicitly:curry(fn, 3). - "Currying vs partial application?" Currying always takes arguments step by step until complete. Partial application fixes some arguments once (like
bind, Lesson 56).
Common mistakes
- Flatten: forgetting to decrease the depth, or checking
typeof item === "object"instead ofArray.isArray. - Curry: comparing with the wrong length, or losing the earlier arguments.
How to say it in an interview
"For flatten I loop over the items and, if an item is an array and depth remains, recursively flatten it with depth minus one and spread the result; for unbounded or very deep nesting I use an explicit stack to avoid stack overflows. For curry I compare the collected arguments with fn.length: once there are enough I call the function, otherwise I return a closure that collects more arguments. fn.length ignores rest and default parameters, so for those I would pass the arity explicitly."
Key words
| Word | Meaning |
|---|---|
| Flatten | Remove nesting from arrays |
| Depth | How many levels of nesting to remove |
| Currying | Taking arguments one step at a time |
| Arity | How many arguments a function expects |
fn.length | The number of declared parameters |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.