Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Created October 26, 2021 12:04
Show Gist options
  • Select an option

  • Save cagataycali/57a03657e564f91846421921e4b02246 to your computer and use it in GitHub Desktop.

Select an option

Save cagataycali/57a03657e564f91846421921e4b02246 to your computer and use it in GitHub Desktop.
[JavaScript] Flatten an array.
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