Skip to content

Instantly share code, notes, and snippets.

@filipesperandio
Last active September 17, 2016 18:55
Show Gist options
  • Save filipesperandio/3b9f884e359366bd4b34136025368330 to your computer and use it in GitHub Desktop.
Save filipesperandio/3b9f884e359366bd4b34136025368330 to your computer and use it in GitHub Desktop.
Flatten array
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