Created
March 19, 2017 16:52
-
-
Save Deminem/fb71fbac39fef73fed477e88667c964a to your computer and use it in GitHub Desktop.
A simple javascript code snippet that provide the flatten method for nested arrays of objects. Raw
This file contains 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
(function() { | |
'use strict'; | |
// create a method which flatten nested arrays of objects | |
Array.prototype.flatten = function() { | |
var flatten = []; | |
this.slice(0).forEach(function(elem) { | |
if (Array.isArray(elem)) { | |
// handle deep level nesting | |
var result = elem.flatten(); | |
flatten = flatten.concat(result); | |
} else { | |
// push the element in the array | |
flatten.push(elem); | |
} | |
}); | |
return flatten; | |
}; | |
// print the array | |
Array.prototype.print = function() { | |
return this.slice(0).toString(); | |
}; | |
// testCase #1 - nested array of integers | |
var testCase1 = [1, 2]; | |
var result1 = testCase1.flatten(); | |
console.log(result1.print()); | |
// testCase #2 - nested array of integers single level | |
var testCase2 = [[1], 2, [3], 4]; | |
var result2 = testCase2.flatten(); | |
console.log(result2.print()); | |
// testCase #3 - nested array of integers multiple level | |
var testCase3 = [[1], 2, [3, [4, 5]], 6]; | |
var result3 = testCase3.flatten(); | |
console.log(result3.print()); | |
// testCase #4 - nested array of integers deep level | |
var testCase4 = [[1], 2, [3, [4, 5, [6, [7, 8, [9, 10]]]]], 11]; | |
var result4 = testCase4.flatten(); | |
console.log(result4.print()); | |
// testCase #5 - nested array of strings | |
var testCase5 = ['1', '2', ['3', '4']]; | |
var result5 = testCase5.flatten(); | |
console.log(result5.print()); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: