简体   繁体   中英

Flattening an array recursively (withoout looping) javascript

I'm practicing recursion and am trying to flatten an array without looping (recursion only). As a first step I did the iterative approach and it worked, but am stuck on the pure recursion version:

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return Array.isArray(arr) ? arr = arr.concat(flattenRecursive(arr)) : flattenRecursive(arr.slice(1))
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
])) //should return [2,7,8,3,1,4,7] but isn't - maximum call stack error


//working version (thanks @Dave!):

function flattenRecursive(arr) {
    if (arr.length === 1) {
        return arr;
    }

    return arr[0].concat(Array.isArray(arr) ? flattenRecursive(arr.slice(1)) : arr);
}

console.log(flattenRecursive([
    [2, 7],
    [8, 3],
    [1, 4], 7
]))

//returns [ 2, 7, 8, 3, 1, 4, 7 ]

Here's a working version that's slightly less verbose.

 //using reduce function flattenRecursive(arr) { return arr.reduce(function(result, a){ return result.concat(Array.isArray(a) ? flattenRecursive(a) : a); }, []); } //without reduce function flattenRecursive2(arr) { if (arr.length === 0) return arr; var head = arr.shift(); if (Array.isArray(head)) return flattenRecursive2(head).concat(flattenRecursive2(arr)); else return [head].concat(flattenRecursive2(arr)); } var testArray = [1,[2, 3],[[4, 5, [6, 7]], [8, 9]], 10]; console.log(flattenRecursive(testArray)); console.log(flattenRecursive2(testArray)); 
 <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 

Sorry, I do not have the reputation to comment. Here are my 2 cents.

1) be careful about your initial condition. Here, it seems that if your input is ̀ arr = [[1,2]] , your function returns [[1,2]] , while you would like it to return [1,2] .

2) in the core of the recursion, you must be sure than you recursively call your function with a smaller argument. Here, you should concat the first element of your array with the flattened rest of the array. The function smaller argument. Here, you should concat the first element of your array with the flattened rest of the array. The function smaller argument. Here, you should concat the first element of your array with the flattened rest of the array. The function slice` may be handy for that.

3) It would be also be possible to use a reduce-like function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM