Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现n层嵌套数组的翻转 #21

Open
Rain120 opened this issue Feb 12, 2022 · 0 comments
Open

实现n层嵌套数组的翻转 #21

Rain120 opened this issue Feb 12, 2022 · 0 comments

Comments

@Rain120
Copy link
Owner

Rain120 commented Feb 12, 2022

实现n层嵌套数组的翻转

输入

[1, [2, [3, [4, null]]]]

输出

[4, [3, [2, [1, null]]]]

实现

function reverseArray(arr) {
    const a = arr.flat(Infinity).filter(Boolean).reverse();
    a.push(null);

    for (let i = a.length - 2; i >= 1; i--) {
        if (i === a.length - 2) {
            a[i] = [a[i], null];
            continue;
        }

        a[i] = [a[i], a[i + 1]]
    }

    return a.slice(0, 2);
}
function reverseArray(arr) {
    function reverse(arr, next) {
        if (arr[1] === null) {
            return [arr[0], next];
        }
        
        next = [arr[0], next ? next : null];
        
        return reverse(arr[1], next);
    }
    
    return reverse(arr, null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant