Created
October 26, 2021 12:04
-
-
Save cagataycali/57a03657e564f91846421921e4b02246 to your computer and use it in GitHub Desktop.
[JavaScript] Flatten an array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = require('assert') | |
| // Null is a value, undefined is undefined. | |
| // That's why we have to consider undefined case. | |
| // Example array of nested elements | |
| const array = [1, [2, 3], [[4, 5]], [undefined], [6, 7], [[[[]]]], [8], [[[[[9]]]]]]; | |
| // Expected output for `flatten(array)` | |
| const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
| const flatten = function (array, result = []) { | |
| // | |
| for (let i = 0; i < array.length; i++) { | |
| const value = array[i]; | |
| // If our value is array, we have to dig down. | |
| if (Array.isArray(value)) { | |
| flatten(value, result); | |
| } else { | |
| if (value !== undefined) { | |
| result.push(value); | |
| } | |
| } | |
| } | |
| return result; | |
| } | |
| assert.deepStrictEqual(flatten(array), expected); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment