Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make intersection between two nested arrays

I'm making translations dynamic, but I'm struggling in the part when I have to show the corresponding object from the other array.

I have two arrays, which have the same model, and what I'm trying to do is, when I search for a translation, I want to show also the corresponding translation from the other language.

For the moment, I can only show the one that you are searching for.

For example: If I search for the sentence Are you sure?, besides the Are you sure? sentence, it should show also the corresponding sentence from the other column language.

Here is a snippet with an example: https://codesandbox.io/s/polished-smoke-n6w6i?file=/src/App.js

Any help would be very appreciated. Thank you in advance!

like image 374
Teuta Koraqi Avatar asked Oct 14 '25 04:10

Teuta Koraqi


1 Answers

The logic is to filter the selected language items by their id, not by their value. The id is taken from the default language items.

This is how

const searchByresourceId = (targetLng, selectedResources) => {
  // get the default language item id
  const ids = selectedResources.map(({languageResources}) => languageResources.map(({id}) => id)).flat();

  return targetLng
    ?.map((item) => {
      const languageResources = item.languageResources.filter(
        (namespace) =>
          ids.includes(namespace.id)
      );
      return {
        ...item,
        languageResources
      };
    })
    .filter((item) => item.languageResources.length > 0);
}

Ans you should change how you set the state

const searchByresourceId = (targetLng, selectedResources) => {
  const ids = selectedResources.map(({languageResources}) => languageResources.map(({id}) => id)).flat();
  return targetLng
    ?.map((item) => {
      const languageResources = item.languageResources.filter(
        (namespace) =>
          ids.includes(namespace.id)
      );
      return {
        ...item,
        languageResources
      };
    })
    .filter((item) => item.languageResources.length > 0);
}

https://codesandbox.io/s/cranky-ellis-ccdhx?file=/src/App.js

The code is not optimized of course, I just demonstrated the logic

like image 187
Mosh Feu Avatar answered Oct 17 '25 01:10

Mosh Feu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!