Blog, COLDSURF

Algorithm - Flattening a Number Array

#algorithm

#js

Problem 1

Flatten [1, [2, 3], [4, 5]]
Solution
function flat(numbers) { var answer = []; answer = numbers; answer = answer.flatMap((v) => v); // Use flatMap to flatten one level deep return answer; } console.log("Problem 1:", flat([1, [2, 3], [4, 5]]));
Explanation: flatMap is used to flatten the array one level deep. It works by flattening each element inside the array. By default, it only flattens one level of nesting.

Problem 2

Flatten [1, [2, 3], [4, 5], [4, [5, 6, [6, 7]]]]
Solution
function flatAll(numbers) { var answer = []; answer = numbers; // Keep flattening while there's any nested array while (answer.some((v) => Array.isArray(v))) { answer = answer.flatMap((v) => v); } return answer; } console.log("Problem 2:", flatAll([1, [2, 3], [4, 5], [4, [5, 6, [6, 7]]]]));
Explanation: Since flatMap only flattens one level of depth, if there are still nested arrays, we need to keep flattening them. The some() function checks if there is any array still nested, and if so, it keeps applying flatMap() until all arrays are flattened.

Additional Tip

You can use the flat() method, which makes the process even simpler. This method accepts a depth parameter, allowing you to flatten nested arrays more easily.
Example:
function flatAll(numbers) { return numbers.flat(Infinity); // Infinity flattens all levels of nested arrays } console.log("Problem 2:", flatAll([1, [2, 3], [4, 5], [4, [5, 6, [6, 7]]]]));
In this example, we use flat() with the Infinity argument to flatten all levels of nested arrays, regardless of how deep the nesting goes.
ā† Go home