2

I have a following array:

['/1', '/1/a', '/1/a/b', '/2', '/2/a', '/2/a/b']

I want to write a function which can return following:

['/1', '/2']

Actually '/1' means parent and '/1/a' means child. Let say we have following json:

[
  {
   a:{
     b: 'b value'
    }
  }
  {
   a:{
     b: 'b value'
    }
  }
  {
   a:{
     b: 'b value'
    }
  }
]

If array is e.g.

['/1/a', '/1/a/b', '/2/a', '/2/a/b']

The function would return following:

['/1/a', '/2/a']

I run jsonpath function it returned the above array. I want to e.g change color of the objects returned from jsonpath.I am displaying json in browser using react, I want to only change the color of parent(i.e.'/1', '/2' ) not the children(i.e. '/1/a', '/1/a/b') to save extra renders, how can I do this? The function could be something like;

filter(val =>  !val.startsWith(parent))

How can I do this? Please help

1 Answer 1

3

You could check if a pattern exists by checking the stored values against the pattern.

This approach takes the pats and checks if some item have more than one longer children.

At the end all parts are joined together.

const
    array = ['/1/a/b', '/1', '/1/a', '/1/a/b/3', '/2', '/2/a', '/2/a/b', '/2/a/c/3', '/11/a', '/11/b', '/11'],
    shortests = array
        .reduce((shortests, string) => {
            const
                keys = string.slice(1).split('/'),
                subset = shortests.filter(t => keys.some((v, i) => v !== t[i]));

            if (subset.length !== shortests.length) return [...subset, keys];
            if (!shortests.some(t => t.every((v, i) => v === keys[i]))) shortests.push(keys);
            return shortests;
        }, [])
        .map(keys => `/${keys.join('/')}`);

console.log(shortests);

Sign up to request clarification or add additional context in comments.

1 Comment

Hi thanks for answers but it return '/0' to '/9'. I have string like '/15', '/699', '/1999'

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.