Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Created August 10, 2015 09:03
Show Gist options
  • Save kidGodzilla/84daa0d96a63e88722a3 to your computer and use it in GitHub Desktop.
Save kidGodzilla/84daa0d96a63e88722a3 to your computer and use it in GitHub Desktop.
A couple of functions to flatten arrays, with tests. See http://jsbin.com/zoqorudoka/edit?js,console
/**
* Test Inputs
*/
a = [[1,2,[3.23,4,"dfger",[5]]],4];
a2 = [[[[[0]], [1]], [[[2,5,6], [3]]], [[4], [5]]]];
/**
* Recursively flatten an array
*/
function flatten (array) {
var result = [];
for (var i = 0; i < array.length; i++) {
var value = array[i];
Array.isArray(value) ? result = result.concat(flatten(value)) : result.push(value);
}
return result;
}
/**
* Flatten an array using a string trick
*/
function flt(a){return (""+a).split(',')}
function fltNums(a){return (""+a).split(',').map(Number)}
/**
* Demonstrate each function with each input
*/
console.log("Flatten mixed types recursively", flatten(a));
console.log("Flatten mixed depths recursively", flatten(a2));
console.log("Flatten mixed types using a string trick", flt(a));
console.log("Flatten mixed depths using a string trick", flt(a2));
console.log("Flatten mixed depths using a string trick, converting each value to a number", fltNums(a2));
/***********
* Testing
***********/
/**
* Simple array comparison
*/
function arraysAreEqual (array, array2) {
return JSON.stringify(array) === JSON.stringify(array2);
}
/**
* Assert a thing to be true
*/
function assert (outcome, description) {
if (!outcome) throw "error attempting to " + description;
}
/**
* Test Battery
*/
function runTests () {
assert(arraysAreEqual(flatten(a), [1, 2, 3.23, 4, "dfger", 5, 4]), "Flatten mixed types recursively");
assert(arraysAreEqual(flatten(a2), [0, 1, 2, 5, 6, 3, 4, 5]), "Flatten mixed depths recursively");
assert(arraysAreEqual(flt(a), ["1", "2", "3.23", "4", "dfger", "5", "4"]), "Flatten mixed types using a string trick");
assert(arraysAreEqual(flt(a2), ["0", "1", "2", "5", "6", "3", "4", "5"]), "Flatten mixed depths using a string trick");
assert(arraysAreEqual(fltNums(a2), [0, 1, 2, 5, 6, 3, 4, 5]), "Flatten mixed depths using a string trick, converting each value to a number");
}
/**
* Test Runner
*/
runTests();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment