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

深度铺平数组 flatten #31

Open
AnnVoV opened this issue Mar 31, 2019 · 0 comments
Open

深度铺平数组 flatten #31

AnnVoV opened this issue Mar 31, 2019 · 0 comments
Labels

Comments

@AnnVoV
Copy link
Owner

AnnVoV commented Mar 31, 2019

const flatten = (array) => {
    return array.reduce((accumulator, currentValue) => {
        if (!Array.isArray(currentValue)) {
            accumulator.push(currentValue);
            return accumulator;
        } else {
            const res = flatten(currentValue);
            accumulator = accumulator.concat(res);
            return accumulator;
        }
    }, []);
};

const flattenES6 = (array) => {
    const flattenArray = array => [].concat(...array);
    const res = array.map((item) => {
        return Array.isArray(item) ? flattenES6(item) : item;
    });
    return flattenArray(res);
};

const arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
const resultES6 = flattenES6(arr);
const result = flatten(arr);
console.log(resultES6);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant