array of strings to tree data structure?

There is data returned from server containing an array of strings as hierarchy like this:

var array = [
 "house.bedroom.bed",
 "house.kitchen.spoon",
 "house.kitchen.knife",
 "house.bedroom.sofa",
 "house.bedroom.tv",
 "plants.trees",
 "house.birds.parrot.grey"
 ]

i have successful made a tree data structure as object out of it to make Output the data in tree form below:

  house
    bedroom
      bed
      sofa
      tv
    kitchen
      spoon
      knife
    birds
      parrot
        grey
  plants
    trees

and is there any way to pick a string? for example of asked "kitchen" i want to return all related to that string like this:

house.kitchen.knife
house.kitchen.spoon

Here the codes that i learned:

function find([key, values], string, temp = []) {
    var result;
    temp = temp.concat(key);
    if (key === string) {
        return temp.slice(1).join('.');
    }
    values.some(a => result = find(a, string, temp));
    return result;
}


var result = array.reduce((r, s) => {
        ('root.' + s).split('.').reduce((a, item) => {
            var array = a.find(([v]) => v === item);
            if (!array) {
                a.push(array = [item, []]);
            }
            return array[1];
        }, r);
        return r;
    }, []).pop();

console.log(find(result, 'kitchen'));
console.log(result);

my output is:

house.kitchen

Solution 1:

I propose to filter the original array

const data = ["house.bedroom.bed","house.kitchen.spoon", "house.kitchen.knife","house.bedroom.sofa","house.bedroom.tv",
 "plants.trees","house.birds.parrot.grey"];
 
 
 const result = data.filter((path) => path.split('.').includes('kitchen'));
 
 console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}