Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // [[1,2,[3]],4]
- var arr = arrayFlatten([[1,2,[3]],4,[1,[2,[3]]]]);
- console.log(arr);
- //Main function
- function arrayFlatten(obj){
- var flattenArray=[];
- //Call recursive funcion sending the array as "reference"
- flatten(obj,flattenArray);
- return flattenArray;
- }
- function flatten(obj, flattenArray){
- //If is an array, go for each element and call the same recursive function
- if(isArray(obj)){
- obj.forEach(function(item){
- flatten(item,flattenArray);
- });
- }
- else{
- //is an integer, just push in the array
- flattenArray.push(obj);
- }
- }
- function isArray(obj) {
- //Check if the object is an array
- return Object.prototype.toString.call(obj) === '[object Array]';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement