Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten Array
const flattenArray = (arr) => {
return arr.reduce((a, v) => {
return a.concat(Array.isArray(v) ? flattenArray(v) : v)
}, []);
}
// ESLint.com
// https://eslint.org/demo#eyJ0ZXh0IjoiY29uc3QgZmxhdHRlbkFycmF5ID0gKGFycikgPT4ge1xuICByZXR1cm4gYXJyLnJlZHVjZSgoYWNjdSwgY3VycikgPT4ge1xuICAgIHJldHVybiBhLmNvbmNhdChBcnJheS5pc0FycmF5KGN1cnIpID8gZmxhdHRlbkFycmF5KGN1cnIpIDogY3VycilcbiAgfSwgW10pO1xufSIsIm9wdGlvbnMiOnsicGFyc2VyT3B0aW9ucyI6eyJlY21hVmVyc2lvbiI6Nywic291cmNlVHlwZSI6InNjcmlwdCIsImVjbWFGZWF0dXJlcyI6e319LCJydWxlcyI6e30sImVudiI6eyJicm93c2VyIjp0cnVlLCJub2RlIjp0cnVlLCJjb21tb25qcyI6dHJ1ZSwic2hhcmVkLW5vZGUtYnJvd3NlciI6dHJ1ZSwid29ya2VyIjp0cnVlLCJhbWQiOnRydWUsIm1vY2hhIjp0cnVlLCJqYXNtaW5lIjp0cnVlLCJqZXN0Ijp0cnVlLCJwaGFudG9tanMiOnRydWUsImpxdWVyeSI6dHJ1ZSwicXVuaXQiOnRydWUsInByb3RvdHlwZWpzIjp0cnVlLCJzaGVsbGpzIjp0cnVlLCJtZXRlb3IiOnRydWUsIm1vbmdvIjp0cnVlLCJwcm90cmFjdG9yIjp0cnVlLCJhcHBsZXNjcmlwdCI6dHJ1ZSwibmFzaG9ybiI6dHJ1ZSwic2VydmljZXdvcmtlciI6dHJ1ZSwiYXRvbXRlc3QiOnRydWUsImVtYmVydGVzdCI6dHJ1ZSwid2ViZXh0ZW5zaW9ucyI6dHJ1ZSwiZXM2Ijp0cnVlLCJncmVhc2Vtb25rZXkiOnRydWV9fX0=
// Test
const arr1 = [[1], [2], [3],[ 4], [5], [6], [7], [8], [9], [10], [11], [12]];
const arr2 = [[1], [2], [3], [4], 5, 6, 7, 8, 9 , [10], [11], [12]];
const arr3 = [[[1, 2]], 3, [4], [5], 6, [7], [8, [9, 10]], [11], 12];
const arr4 = [[1, 2], [[[[3, 4, 5]]]], 6, [7, [[[8], [9], 10]], 11], 12];
const arr5 = [1, 2, [3, 4, 5, [[[6, 7, [8, 9]]]]], 10, 11, 12];
const arr6 = [1, 2, [[[[[[[3, 4, [[[[5, [6], [7]]]]], [[[[[8, 9 , 10]]]]]]]]]]]], 11, 12];
console.log(flattenArray(arr1));
console.log(flattenArray(arr2));
console.log(flattenArray(arr3));
console.log(flattenArray(arr4));
console.log(flattenArray(arr5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment