Last active
September 17, 2016 18:55
-
-
Save filipesperandio/3b9f884e359366bd4b34136025368330 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
function arrayEquals(actual, expected) { | |
return actual.every(function(element, i) { | |
if (Array.isArray(element)) { | |
return arrayEquals(element, expected[i]); | |
} | |
return element === expected[i]; | |
}) | |
} | |
function flatten (arr) { | |
var result = []; | |
for (var i=0; i < arr.length; i++) { | |
if(Array.isArray(arr[i])) { | |
var nested = flatten(arr[i]); | |
result = result.concat(nested); | |
} else { | |
result.push(arr[i]); | |
} | |
} | |
return result | |
} | |
function assert (actual, expected) { | |
var result = arrayEquals(actual, expected); | |
console.log(result ? 'SUCCESS' : ('FAILURE: ' + JSON.stringify(actual) + ' not equal to ' + JSON.stringify(expected))); | |
} | |
var testArr1 = [1, 2, [3, 4]]; | |
var testArr2 = [1, [2, [10, 20], 3, 4], 5, [6, 7]]; | |
assert(flatten(testArr1), [1, 2, 3, 4]); // SUCCESS | |
assert(flatten(testArr2), [1, 2, 10, 20, 3, 4, 5, 6, 7]); // SUCCESS | |
// using language trick to flatten - 1 level deep arrays | |
assert([].concat.apply([], testArr1), [1, 2, 3, 4]); // SUCCESS | |
assert([].concat.apply([], testArr2), [1, 2, [10, 20], 3, 4, 5, 6, 7]); // SUCCESS | |
assert([].concat.apply([], testArr2), [1, 2, 10, 20, 3, 4, 5, 6, 7]); // FAILURE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment