Skip to content

Instantly share code, notes, and snippets.

@Deminem
Created March 19, 2017 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deminem/fb71fbac39fef73fed477e88667c964a to your computer and use it in GitHub Desktop.
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
(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());
})();
@Deminem
Copy link
Author

Deminem commented Mar 19, 2017

Result:

TestCase#1: 1,2
TestCase#2: 1,2,3,4
TestCase#3: 1,2,3,4,5,6
TestCase#4: 1,2,3,4,5,6,7,8,9,10,11
TestCase#5: 1,2,3,4

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