Search code examples
javascriptgroupinglodash

Lodash find and keep index of items in an array


I am trying to find, group and keep indices of keywords in an array and store it as an object.

So say I have an object like so:

{
  "foo": ["bar", "bazz"],
  "boo": ["far", "fuzz"]
}

And I have a sentence like so:

Lorem ipsum dolor sit bar, consectetur adipiscing bazz. Nam luctus fringilla bazz. Suspendisse mauris far, aliquam in far nec, placerat quis leo. fuzz fuzz,

I wanted an output like so:

{
  "foo": [
    {"bar": [22]},
    {"bazz": [50, 77]}
  ],
  "boo": [
    {"far": [102, 118]},
    {"fuzz": [146, 151]}
  ]
}

I am trying to highlight the text as well as keep it categorized.


Solution

  • If you want to find indexes, you can use the following code

    const a =
      "Lorem ipsum dolor sit bar, consectetur adipiscing bazz. Nam luctus fringilla bazz. Suspendisse mauris far, aliquam in far nec, placerat quis leo. fuzz fuzz,";
    
    const b = {
      foo: ["bar", "bazz"],
      boo: ["far", "fuzz"]
    };
    
    function groupAndFindIndexes(text, groups) {
      return Object.keys(b).reduce((store, id) => {
        store[id] = b[id].map(word => {
          const reg = new RegExp(word, "g");
          const items = [];
          let find = reg.exec(a);
          while (find) {
            items.push(find.index);
            find = reg.exec(a);
          }
          return { [word]: items };
        });
        return store;
      }, {});
    }
    
    const result = groupAndFindIndexes(a, b);
    

    Result is:

    {
      "foo": [
        {
          "bar": [22]
        },
        {
          "bazz": [50, 77]
        }
      ],
      "boo": [
        {
          "far": [102, 118]
        },
        {
          "fuzz": [146, 151]
        }
      ]
    }