Search code examples
reactjsgraphqlmappingfilteringstrapi

Remove duplicate JSX elements | React Strapi graphql


Long story short, i have and array of JSX elements, that looks something like this:

              <ChatListCard
                key={index}
                prop1={prop1}
                prop2={prop2}
                prop3={prop3}
              />

I get the props for these "Cards" from two different tables in Strapi/Graphql API, so I do something like this:

[].concat(
  array1.map((item,index)=> <Card key={index} prop1={item.prop1} ... />),
  array2.map((item,index)=> <Card key={index} prop1={item.prop1} ... />)
)

The problem is that array1 and array2 contain some "items" that are identical, and need to be filtered out. Is there a way to do it, using JS:

[].concat(...).filter((magic)=> magic but filtered) //use the filter here

, or i should do it in GraphQL. (I have already used where clause in there to filter out only the items that I do not need)

query ProposalsAndRequests($input:String!){
  proposals(where: {_or:[
    {owner:{email:$input}}
    {task:{owner:{email:$input}}}
  ]},sort:"created_at:desc"){
    id
    ...
    }
  }
  chatRequests(where:{_or:[
    {users_permissions_user:{email:$input}}
    {task:{owner:{email:$input}}}
  ]},sort:"created_at:desc"){
    id
    ...
  }
}
  • note: chatRequests and Proposals contain identical fields, they just serve different purposes elsewhere in the site
  • the users_permissions_user and owner are also the same relation

Solution

  • You can do it using the "Set" datastructure in js. const set = new Set(arr);. Sets cant have duplicates! :-) but they can have identical objects if the references are not the same.

    For a more complex filter, use .reduce function to accumilate only uniques.

    Or, you could remove the duplicates by bruteforce it with something like:

    const noDubs = [];
    
    myArr.foreach(item => {
      if(!noDubs.some(entry = entry.special.property === item.special.property) noDubs.push(item);
    });