Skip to content

Instantly share code, notes, and snippets.

@rofrol
Last active January 9, 2020 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofrol/666879b603c1a8f57f9fda59cc3a6dd6 to your computer and use it in GitHub Desktop.
Save rofrol/666879b603c1a8f57f9fda59cc3a6dd6 to your computer and use it in GitHub Desktop.
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