Let’s say an array in Javascript is defined like this:
1 | var arr = [1, [2, 3], 4, [5, 6, [7, 8], 9]]; |
var arr = [1, [2, 3], 4, [5, 6, [7, 8], 9]];
and our target is to unroll (or flatten) it so the output array becomes:
1 | var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; |
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
Our approach is to go through each element of array (if it is array) recursively and push to a local/scoped array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // https://helloacm.com/how-to-unrollflatten-array-recursively-using-javascript/ function unrollArray(x) { let result = []; let func = function(arr) { if (Array.isArray(arr)) { let len = arr.length; for (let i = 0; i < arr.length; ++ i) { func(arr[i]); // do this recursively } } else { result.push(arr); // put the single element to result } } func(x); return result; } |
// https://helloacm.com/how-to-unrollflatten-array-recursively-using-javascript/ function unrollArray(x) { let result = []; let func = function(arr) { if (Array.isArray(arr)) { let len = arr.length; for (let i = 0; i < arr.length; ++ i) { func(arr[i]); // do this recursively } } else { result.push(arr); // put the single element to result } } func(x); return result; }
We use Array.isArray to check if the element itself is an array. Please note that we define the local function that is only visible inside the function block i.e. unrollArray.
1 2 | var x = unrollArray([1, 3, [5, 7, [9, 11]], 13]); // x = [1, 3, 5, 7, 9, 11, 13]; |
var x = unrollArray([1, 3, [5, 7, [9, 11]], 13]); // x = [1, 3, 5, 7, 9, 11, 13];
You could also use the reduce function to merge the Javascript array as well.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
265 wordsloading...
Last Post: How to Create a WordPress Page to List All Comments?
Next Post: How to Kill Multiple Processes (Tasks) by Name using VBScript?
It’s good to know how to do some recursive stuff like this. Definitely something that you can’t forego when working with javascript.
I know this article is not super recent, but maybe an update is in order to explain that JS now has a `.flat` method on arrays. So this could be written like:
`[1, [2, 3], 4, [5, 6, [7, 8], 9]].flat(Infinity)` to achieve the same result.
The `Infinity` is needed to go more than 1 level deep (the default).
Thank you!