Last active
January 9, 2020 12:00
-
-
Save rofrol/666879b603c1a8f57f9fda59cc3a6dd6 to your computer and use it in GitHub Desktop.
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
function flatten(array) { | |
let i = 0; | |
while (i < array.length) { | |
if (!Array.isArray(array[i])) { | |
i++ | |
} else { | |
array.splice(i, 1, ...array[i]) | |
} | |
} | |
} | |
const errorMsg = 'array is not flatten'; | |
function test() { | |
let array = [[1,2,[3]],4] | |
flatten(array) | |
const shouldBe = [1,2,3,4] | |
console.assert(arraysEqual(array, shouldBe), {array, errorMsg}) | |
} | |
// https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript/16436975#16436975 | |
function arraysEqual(a, b) { | |
if (a === b) return true; | |
if (a == null || b == null) return false; | |
if (a.length != b.length) return false; | |
// If you don't care about the order of the elements inside | |
// the array, you should sort both arrays here. | |
// Please note that calling sort on an array will modify that array. | |
// you might want to clone your array first. | |
for (var i = 0; i < a.length; ++i) { | |
if (a[i] !== b[i]) return false | |
} | |
return true | |
} | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment