Remove matching strings from array

Viewed 49

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 Answers

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

Related