Skip to content

Instantly share code, notes, and snippets.

@brandonweis
Created June 9, 2020 09:45
Show Gist options
  • Select an option

  • Save brandonweis/228fa7b9944adeeb47236e7b4e65430f to your computer and use it in GitHub Desktop.

Select an option

Save brandonweis/228fa7b9944adeeb47236e7b4e65430f to your computer and use it in GitHub Desktop.
/*
Implement the array flat function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
var arr1 = [1, 2, [3, 4]];
arr1.flat(); // [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(); // [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Extension: remove empty slots in flattened arrays
var arr5 = [1, 2, , 4, 5];
arr5.flat(); // [1, 2, 4, 5]
var arr6 = [1, 2, , [4, ,5]];
arr6.flat(); // [1, 2, [4, ,5]]
*/
Array.prototype.flat = function customFlat(dept = Infinity) {
const arr = this;
return this.reduce((acc, curr) => {
if(dept > 0 && Array.isArray(curr)){
dept--;
return [...acc, ...customFlat.call(curr, dept)]
}
return [...acc, curr]
}, []);
}
console.log([1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]].flat());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment