Skip to content

Instantly share code, notes, and snippets.

@timothytran
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timothytran/d0e11217c5c4266125d2 to your computer and use it in GitHub Desktop.
Save timothytran/d0e11217c5c4266125d2 to your computer and use it in GitHub Desktop.
// check if value is an integer
function isInt(value){
return Number(value) === value && value % 1 === 0;
}
// function to flatten an array
function flatten(data, isInteger) {
var result = [];
// initialize data if input is undefined/empty
data = data || [];
// loop through the input array to process each element
for (var i = 0; i < data.length; i++) {
// check to see if the current item is an array itself
if (Array.isArray(data[i])) {
// if the item is an array then recursively call this function again and join the item to the result array
result = result.concat(flatten(data[i], isInteger));
} else {
// once we find an item that isn't an array, push it to the result array.
if (isInteger) {
// if isInteger is true we will need to check whether the item is an integer before adding it to the result array
if (isInt(data[i])) {
result.push(data[i]);
}
} else {
result.push(data[i]);
}
}
}
// return the flatten array
return result;
}
/* usage sample */
// input array
var inputArray = [[1,2,[3, [4]]],5, 'a', ['z', 6], 7, 8];
// flatten array
var outputArray = flatten(inputArray);
// flatten array with integer only
var integerArray = flatten(inputArray, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment