Skip to content

Instantly share code, notes, and snippets.

@mikeumus
Last active March 28, 2016 09:43
Show Gist options
  • Save mikeumus/b00e333da5467666c501 to your computer and use it in GitHub Desktop.
Save mikeumus/b00e333da5467666c501 to your computer and use it in GitHub Desktop.
Simple Int Array Flattener/De-nester in ECMAScript 5
// Simple Int Array Flattener/De-nester in ECMAScript 5!
// Interactive version on Plunker: https://plnkr.co/edit/fjqPJmzxpTFQu8VsToXK
(function(){ // Immediately Invoked Function Expression (iife) for safety closure.
var firstArray = [[1,2,[3]],4]; // Test array #1, 3 nests deep.
var secondArray = [[1,2,[3,[5]]],4]; // Test array #2, 4 nests deep!
var flatten = function(arr){ // Our flatten function take an array.
var flatArr = []; // New empty array.
var newArr = arr.join().split(","); // Flatten or De-nest our nested array into equal string values.
for(var i=0; i<newArr.length; i++){ // Loop through new flattened string array.
flatArr.push(parseInt(newArr[i])); // Push new int values into new array.
}
console.log(flatArr); // Logging out to console so we may see the result.
}
flatten(firstArray); // Call the function for our first test array.
flatten(secondArray); // And then call it again for the second array.
})(); // Close the closure and then immediately call itself.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment