0

Let us say I have a string array with values like -

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

When I have to display this array, I want to display it like this -

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

What should be my approach? I should use group by or filter or what? I am using angular 6 and material UI.

4
  • You will have to group, but not sure if angular provides any in-built one. You can create a custom one though Commented Jan 24, 2019 at 9:30
  • Can you shed some more light please? Commented Jan 24, 2019 at 9:34
  • Loop with ngfor to display on html, angular.io/guide/… Commented Jan 24, 2019 at 9:35
  • Post your input JSON Commented Jan 24, 2019 at 9:37

1 Answer 1

3

I have a begin of what you need :

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);

input :

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

output :

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

Edit :

You can also use reduce statement wich works pretty well too :)

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.