You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从含父子层级关系的数组中筛选顶层层级元素?

筛选数组中顶层层级元素的最优方案

我需要一种方法,从包含父子层级关系对象的数组里筛选出顶层层级元素。以下是几个具体示例:

第一个示例数组:

[
    {
        "Code": "1A",
        "name": "Western Europe",
        "hierarchy": "World/"
    },
    {
        "Code": "AT",
        "name": "Austria",
        "hierarchy": "World/ Western Europe/"
    },
    {
        "Code": "NL",
        "name": "Netherlands",
        "hierarchy": "World/ Western Europe/"
    }
]

输出应为第一个对象,因为Western Europe是Austria和Netherlands的父级。

第二个示例数组:

[
    {
        "Code": "WO",
        "name": "World",
        "hierarchy": ""
    },
    {
        "Code": "NA",
        "name": "North America",
        "hierarchy": "World/"
    },
    {
        "Code": "NL",
        "name": "Netherlands",
        "hierarchy": "World/ Western Europe/"
    }
]

输出为World,因为它是顶层层级。

第三个示例数组:

[
    {
        "Code": "1A",
        "name": "Western Europe",
        "hierarchy": "World/"
    },
    {
        "Code": "NA",
        "name": "North America",
        "hierarchy": "World/"
    },
    {
        "Code": "US",
        "name": "United States",
        "hierarchy": "World/ North America/"
    },
    {
        "Code": "NL",
        "name": "Netherlands",
        "hierarchy": "World/ Western Europe/"
    },
    {
        "Code": "RS",
        "name": "Russia",
        "hierarchy": "World/ Eastern Europe/"
    }
]

输出应为Western Europe、North America和Russia(由于列表中没有Eastern Europe,因此Russia属于其层级的顶层)。

另外,我有一个可传入Code获取层级结构的函数:

getParentChildHierarchy(string Code) { //some code here }

函数调用示例:

  • 输入: AT
  • 输出: WO>1A>AT

求最优解决方案。

内容的提问来源于stack exchange,提问作者Purushottam Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:55:24