Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:57
Show Gist options
  • Save rfprod/3f98eaea718b002eb2e3 to your computer and use it in GitHub Desktop.
Save rfprod/3f98eaea718b002eb2e3 to your computer and use it in GitHub Desktop.
Steamroller
function steamroller(arr) {
var outputArr = [];
var needsFlatten = false;
for (var z=0;z<arr.length;z++){
/* remove objects - optional, remove comment if object removal is needed
if (typeof arr[z] === 'object' && !isArray(arr[z])){
arr.splice(z,1);
}
*/
while (isArray(arr[z])){
arr = flatten(arr);
}
}
function flatten(arr){
var firstPrt = [];
var secondPrt = [];
for (var i=0;i<arr.length;i++){
var curVal = arr[i];
var isIt = isArray(curVal);
if (isIt && curVal !== ""){
firstPrt = arr.slice(0,i);
secondPrt = arr.slice(i+1,arr.length);
arr = [];
arr = arr.concat(firstPrt);
for (var j=0;j<curVal.length;j++){
arr = arr.concat(curVal[j]);
}
arr = arr.concat(secondPrt);
}
}
return arr;
}
function isArray(inputArr) {
return inputArr.constructor.toString().indexOf("Array") > -1;
}
return arr;
}
steamroller([1, {}, [3, [[4]]]]);

Steamroller

Flattens a nested array with account for varying levels of nesting.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment