Home > Enterprise >  find count of duplicate properties in array of Objects in Reactjs
find count of duplicate properties in array of Objects in Reactjs

Time:08-29

i have following Code which is working fine `

someVar.getNftsByCollections(['abcs']).then((obj) => {  
obj.filter(nft => nft.sold === true)
    .map(nft => console.log(nft)) 
  });
 
})`

and its consol me the data like this

          { name: "Common Pass"
          owner: "abc1"
          placeholderNft: false
          position: 1509
          price: 1000}

Now i have 100 of objects like that which is am consoling but now i want to find duplicates owners count so how can i extend my code .In simple words e.g. there are other records with same owner abc1 like around 12 so how can i achieve this

CodePudding user response:

var dublicates = {}
someVar.getNftsByCollections(['abcs']).then((obj) => {  
obj.filter(nft => {
  dublicates[nft.owner] = dublicates[nft.owner] ? dublicates[nft.owner]   1 : dublicates[nft.owner]
  return(nft.sold === true)
})
    .map(nft => console.log(nft)) 
  });
})

actural_dublicate =Object.keys(dublicates).filter(key => dublicates[key] > 1)

CodePudding user response:

You can use a reduce to iterate over this array and generate a count in the format.

{ owner: 'abc1', count: 12 }

With that you'll have:

someVar.getNftsByCollections(['abcs']).then((obj) => {  
  .filter((nft) => nft.sold)
  .reduce((accObj, nft) => {
      const owner = nft.owner;
      const accountedOwner = accObj.find((obj) => obj.owner === owner);
      if (!accountedOwner) {
        accObj.push({ owner, count: 1 });
      } else {
        accountedOwner.count  ;
      }
      return accObj;
    }, []);
})

You can play with that at:
https://codesandbox.io/s/happy-frog-bx6kxm?file=/src/App.js

  • Related