【问题标题】:Nested Group by based on string value Angular 6基于字符串值Angular 6的嵌套分组
【发布时间】:2019-06-17 23:39:08
【问题描述】:

假设我有一个字符串数组,其值类似于 -

animal
animal.mammal
animal.bird
animal.reptile
animal.mammal.human
animal.mammal.horse
animal.bird.crow
animal.reptile.snake

当我必须显示这个数组时,我想这样显示 -

-animal
  -animal.mammal
    -animal.mammal.human
    -animal.mammal.horse
  -animal.bird
    -animal.bird.crow
  -animal.reptile
    -animal.reptile.snake

我的方法应该是什么?我应该使用 group by 或 filter 还是什么? 我正在使用 Angular 6 和材质 UI。

【问题讨论】:

  • 您必须进行分组,但不确定 Angular 是否提供任何内置分组。你可以创建一个自定义的
  • 你能再解释一下吗?
  • ngfor循环显示在html上,angular.io/guide/…
  • 发布您的输入 JSON

标签: javascript arrays angular group-by filtering


【解决方案1】:

我有你需要的开始:

const groups = arr => {
    const res = [];
    arr.forEach(v => {
        let current = res
        const splits = v.split('.');
        splits.forEach(s => {
            if (current[s] === undefined) {
                current[s] = [];
            }
            current = current[s];
        });
        current.push(v);
    }
    return res;

 groups(yourArrayHere);

输入:

const arr = ['animal', 'animal.mammal', 'animal.mammal.human'];

输出:

[
   'animal': [
       0: 'animal',
       'animal.mammal': [
           0: 'animal.mammal.human'
       ]
   ]
]

编辑:

你也可以使用 reduce 语句,效果也很好:)

const groups = arr => {
    return arr.reduce((acc, v) => {
       let current = acc
        v.split('.').forEach(s => {
            if (current[s] === undefined) {
                current[s] = [];
            }
            current = current[s];
        });
        current.push(v);
        return acc;
    }, []);
};

groups(theArray);

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 1970-01-01
    • 2017-07-20
    • 2015-02-14
    • 2015-10-31
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多