Created
November 8, 2019 05:58
-
-
Save oklandon/c9336f9b9f0ee5bccdbd99bc51ef82bd to your computer and use it in GitHub Desktop.
flatten array
This file contains 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
// loops through the array recursively and appends items until the 'current' list item is not an array | |
const flatsy = (arr, carry=[]) => | |
Array.isArray(arr) ? arr.reduce((acc, curr) => | |
Array.isArray(curr) | |
? flatsy(curr, acc) | |
: [...acc, curr] | |
, | |
carry | |
) : arr | |
const isEqual = (a,b) => { | |
const length = a.length | |
if(!length || a.length !== b.length) { | |
return false | |
} | |
for(let i = 0; i <= length; i++) { | |
if (a[i] !== b[i]){ | |
return false | |
} | |
} | |
return true | |
} | |
// tests | |
const arr1 = [[1,2,[3]],4] | |
const des1 = [1, 2, 3, 4] | |
if (isEqual(des1, flatsy(arr1))){ | |
console.log('can flatten example array') | |
} | |
const arr2 = [[1,2,[3,[2,3,[3]]],4], [3,[2,5,23,8,1]]] | |
const des2 = [ 1, 2, 3, 2, 3, 3, 4, 3, 2, 5, 23, 8, 1 ] | |
if (isEqual(des2, flatsy(arr2))) { | |
console.log('can handle deeply nested weirdy array') | |
} | |
const one = 1 | |
if (flatsy(one) == one) { | |
console.log('returns the input if not an array') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment