Javascript Reverse Alignment Arrays

I am training and trying to write a recursive function to smooth the array. The code goes here:

function flatten() { var flat = []; for (var i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Array) { flat.push(flatten(arguments[i])); } flat.push(arguments[i]); } return flat; } 

The problem is that if I pass an array or nested arrays there, I get the error "maximum call stack size". What am I doing wrong?

+13
javascript arrays recursion
source share
14 answers

The problem is how you pass the processing of the array, if this value is an array, then you keep calling it, causing an infinite loop

 function flatten() { var flat = []; for (var i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Array) { flat.push.apply(flat, flatten.apply(this, arguments[i])); } else { flat.push(arguments[i]); } } return flat; } 

Demo: Fiddle

Here's a more modern version:

 function flatten(items) { const flat = []; items.forEach(item => { if (Array.isArray(item)) { flat.push(...flatten(item)); } else { flat.push(item); } }); return flat; } 
+21
source share

The Astrakel approach ...

 function flatArray([x,...xs]){ return x !== undefined ? [...Array.isArray(x) ? flatArray(x) : [x],...flatArray(xs)] : []; } var na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10]; fa = flatArray(na); console.log(fa); 
+3
source share

There is no else statement in your code, and the recursive call is incorrect (you pass the same array over and over, and not pass its elements).

Your function can be written as follows:

 function flatten() { // variable number of arguments, each argument could be: // - array // array items are passed to flatten function as arguments and result is appended to flat array // - anything else // pushed to the flat array as-is var flat = [], i; for (i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Array) { flat = flat.concat(flatten.apply(null, arguments[i])); } else { flat.push(arguments[i]); } } return flat; } // flatten([[[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]], [[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]]]); // [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] 
+2
source share

If someone is looking to smooth out an array of objects (like tree ), then here is the code:

 function flatten(items) { const flat = []; items.forEach(item => { flat.push(item) if (Array.isArray(item.children) && item.children.length > 0) { flat.push(...flatten(item.children)); delete item.children } delete item.children }); return flat; } var test = [ {children: [ {children: [], title: '2'} ], title: '1'}, {children: [ {children: [], title: '4'}, {children: [], title: '5'} ], title: '3'} ] console.log(flatten(test)) 
+2
source share

If you assume that your first argument is an array, you can make it pretty simple.

 function flatten(a) { return a.reduce((flat, i) => { if (Array.isArray(i)) { return flat.concat(flatten(i)); } return flat.concat(i); }, []); } 

If you want to smooth out multiple arrays, just compare them before going through.

+2
source share

If the element is an array, we simply add all the other elements to this array

 function flatten(array, result) { if (array.length === 0) { return result } var head = array[0] var rest = array.slice(1) if (Array.isArray(head)) { return flatten(head.concat(rest), result) } result.push(head) return flatten(rest, result) } console.log(flatten([], [])) console.log(flatten([1], [])) console.log(flatten([1,2,3], [])) console.log(flatten([1,2,[3,4]], [])) console.log(flatten([1,2,[3,[4,5,6]]], [])) console.log(flatten([[1,2,3],[4,5,6]], [])) console.log(flatten([[1,2,3],[[4,5],6,7]], [])) console.log(flatten([[1,2,3],[[4,5],6,[7,8,9]]], [])) 
+2
source share
 [...arr.toString().split(",")] 

Use the toString() method in Object . Use the distribution operator (...) to create an array of strings and split it into "," .

Example:

 let arr =[["1","2"],[[[3]]]]; // output : ["1", "2", "3"] 
+2
source share

This is Vanilla JavaScript solution for this problem

 var _items = {'keyOne': 'valueOne', 'keyTwo': 'valueTwo', 'keyThree': ['valueTree', {'keyFour': ['valueFour', 'valueFive']}]}; // another example // _items = ['valueOne', 'valueTwo', {'keyThree': ['valueTree', {'keyFour': ['valueFour', 'valueFive']}]}]; // another example /*_items = {"data": [{ "rating": "0", "title": "The Killing Kind", "author": "John Connolly", "type": "Book", "asin": "0340771224", "tags": "", "review": "i still haven't had time to read this one..." }, { "rating": "0", "title": "The Third Secret", "author": "Steve Berry", "type": "Book", "asin": "0340899263", "tags": "", "review": "need to find time to read this book" }]};*/ function flatten() { var results = [], arrayFlatten; arrayFlatten = function arrayFlattenClosure(items) { var key; for (key in items) { if ('object' === typeof items[key]) { arrayFlatten(items[key]); } else { results.push(items[key]); } } }; arrayFlatten(_items); return results; } console.log(flatten()); 
+1
source share

This should work

 function flatten() { var flat = [ ]; for (var i = 0; i < arguments.length; i++) { flat = flat.concat(arguments[i]); } var removeIndex = [ ]; for (var i = flat.length - 1; i >= 0; i--) { if (flat[i] instanceof Array) { flat = flat.concat(flatten(flat[i])); removeIndex.push(i); } } for (var i = 0; i < removeIndex.length; i++) { flat.splice(removeIndex - i, 1); } return flat; } 
0
source share

Other answers have already indicated the source of the OP code failure. By writing more descriptive code, the problem literally boils down to "detecting the / -reduce / -concat-recursion array" ...

 (function (Array, Object) { //"use strict"; var array_prototype = Array.prototype, array_prototype_slice = array_prototype.slice, expose_internal_class = Object.prototype.toString, isArguments = function (type) { return !!type && (/^\[object\s+Arguments\]$/).test(expose_internal_class.call(type)); }, isArray = function (type) { return !!type && (/^\[object\s+Array\]$/).test(expose_internal_class.call(type)); }, array_from = ((typeof Array.from == "function") && Array.from) || function (listAlike) { return array_prototype_slice.call(listAlike); }, array_flatten = function flatten (list) { list = (isArguments(list) && array_from(list)) || list; if (isArray(list)) { list = list.reduce(function (collector, elm) { return collector.concat(flatten(elm)); }, []); } return list; } ; array_prototype.flatten = function () { return array_flatten(this); }; }(Array, Object)); 

borrowing code from one of the other answers as proof of concept ...

 console.log([ [[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]], [[[0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2]]] ].flatten()); //[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, ..., ..., ..., 0, 1, 2] 
0
source share

Here's a recursive reduction implementation taken from an absurdity that mimics lodash _.concat()

It can accept any number of arguments to an array or not an array. Arrays can be of any depth level. As a result, you get one array of smoothed values.

 export const concat = (...arrays) => { return flatten(arrays, []); } function flatten(array, initial = []) { return array.reduce((acc, curr) => { if(Array.isArray(curr)) { acc = flatten(curr, acc); } else { acc.push(curr); } return acc; }, initial); } 

Any number of arrays or non-arrays can be used as input.

Source: I am the author of the absurd

0
source share

Modern but not cross-browser

 function flatten(arr) { return arr.flatMap(el => { if(Array.isArray(el)) { return flatten(el) } else { return el; } }) 

}

0
source share

The clean way to flatten an Array in 2019 using ES6 you can use flat() :

 const array = [1, 1, [2, 2], [[3, [4], 3], 2]] // All layers array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2] // Varying depths array.flat() // [1, 1, 2, 2, Array(3), 2] array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2] array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2] array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2] array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2] 

Mozilla Docs

Can I use - 80% Sept. 2019 year

0
source share

you must add a stop condition for recursion.

as an example if len (arguments [i]) == 0 return

-one
source share

All Articles