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

【JS】数组扁平化 #107

Open
Easay opened this issue May 29, 2021 · 1 comment
Open

【JS】数组扁平化 #107

Easay opened this issue May 29, 2021 · 1 comment
Labels

Comments

@Easay
Copy link
Owner

Easay commented May 29, 2021

reduce方法

function flatten1(arr){
    return arr.reduce((pre,cur)=>{
        Array.isArray(cur)?pre = pre.concat(flatten1(cur)):pre.push(cur);
        return pre;
    },[]);
}

循环

function flatten2(arr){
    let res = [];
    for(let i=0;i<arr.length;i++){
        if(Array.isArray(arr[i])){
            res = res.concat(flatten2(arr[i]));
        }else{
            res.push(arr[i]);
        }
    }
    return res;
}

在原数组上修改

// 原数组上修改
function flatten3(arr){
    for(let i=0;i<arr.length;i++){
        if(Array.isArray(arr[i])){
            flatten3(arr[i]);
            let len = arr[i].length;
            arr.splice(i,1,...arr[i]);
            i = i+len-1;
        }
    }
}
let c = [1,[2,3,[4,5,6]]];
flatten3(c);
console.log(c);
@Easay Easay added the JS label May 29, 2021
@Easay
Copy link
Owner Author

Easay commented Aug 23, 2021

数据扁平化并排序

function flatten(arr){
    const dfs = function(arr){
        return arr.reduce((pre,cur)=>{
            Array.isArray(cur)?pre=pre.concat(dfs(cur)):pre.push(cur)
            return pre
        },[])
    }
    const resultArr = dfs(arr)
    resultArr.sort((a,b)=>a-b)
    return resultArr
}
const arr = [[1,2,3],[4,5],9,8,7]
console.log(flatten(arr))

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