Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

【编程进阶】算法 — 递归删除指定层级

输入:

const arrs = [
    {
        name: '广东',
        children: [
            {
                name: '深圳',
                children: [
                    {
                        name: '南山区',
                        children: []
                    }
                ]
            },
            {
                name: '广州',
                children: [
                    {
                        name: '白云区',
                        children: []
                    }
                ]
            }
        ]
    },
    {
        name: '上海',
        children: [
            {
                name: '浦东新区',
                children: []
            }
        ]
    },
    {
        name: '北京',
        children: [
            {
                name: '朝阳区',
                children: []
            }
        ]
    }
]

输出:

[
    {
        name: '广东',
        children: [
            {
                name: '深圳',
                children: []
            },
            {
                name: '广州',
                children: []
            }
        ]
    },
    {
        name: '上海',
        children: []
    },
    {
        name: '北京',
        children: []
    }
]

如上所示,删除了区的那一层,保留到市。

function removeLevel(arrs) {
    // todo
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function removeLevel(arr) {
  function map(arr) {
        return isCity(arr) ? [] : arr.map(v => ({...v, children: map(v.children)}))
  }
  function isCity(arr) {
    return arr.length && arr[0].name.includes('区');
  }
  return map(arr)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...