Created
May 13, 2017 01:42
-
-
Save alejandrolechuga/56c633c188d7102c5ea4c018a21aed19 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Array flatten Technique | |
var oneDepth = [[1], [2], [3], [4], [6], 7, 8]; | |
var multiDepth = [[1, [2, 3], [4]], [5], [3, [4, 5]], [6], [7], 7, [[[[[8]]]]]]; | |
// flatten one level | |
// function flattenOneLevel(array) { | |
// var results = []; | |
// for (var i = 0; i < array.length; i++) { | |
// if (Array.isArray(array[i])) { | |
// results = results.concat(array[i]); | |
// } else { | |
// results.push(array[i]); | |
// } | |
// } | |
// return results; | |
// } | |
function flattenOneLevel(array) { | |
return [].concat.apply([], array); | |
} | |
//console.log(flattenOneLevel(oneDepth)); | |
// flatten queue technique | |
// [1] + [[2], [3]] => [1, [2], [3]] | |
function flattenQueue(array) { | |
var results = []; | |
var queue = array; | |
while(queue.length !== 0) { | |
var nextElement = queue.shift(); | |
if (Array.isArray(nextElement)) { | |
queue = [].concat(nextElement, queue); | |
} else { | |
results.push(nextElement); | |
} | |
} | |
return results; | |
} | |
// console.log(flattenQueue(oneDepth)); | |
// console.log(flattenQueue(multiDepth)); | |
// flatten recursive | |
function flattenRec(array) { | |
return array.reduce(function (acc, element) { | |
return acc.concat(Array.isArray(element) ? flattenRec(element) : element ); | |
}, []); | |
} | |
// console.log(flattenRec(oneDepth)); | |
// console.log(flattenRec(multiDepth)); | |
// flatten recursive with depth | |
function flattenDepth(array, depth) { | |
if (depth === 0) return array; | |
return array.reduce(function (acc, element) { | |
return acc.concat(Array.isArray(element) ? flattenDepth(element, depth - 1) : element ); | |
}, []); | |
} | |
console.log(flattenDepth(oneDepth, 1)); | |
console.log(flattenDepth(multiDepth, 5)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment