How to Unroll/Flatten Array Recursively using Javascript?


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];
JS How to Unroll/Flatten Array Recursively using Javascript? code code library javascript

NodeJs / Javascript

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 words
Last Post: How to Create a WordPress Page to List All Comments?
Next Post: How to Kill Multiple Processes (Tasks) by Name using VBScript?

The Permanent URL is: How to Unroll/Flatten Array Recursively using Javascript?

2 Comments

  1. David Marr

Leave a Reply