Home > database >  How to get Distinct Values based on two attributes
How to get Distinct Values based on two attributes

Time:10-17

Suppose I'm having data like

const array = 
[
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"}
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"}
   { "CategoryDesc": "FRD" ,"SubCatDesc":"VRD"}
   { "CategoryDesc": "FRD" ,"SubCatDesc":"VRD"}
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"}
   { "CategoryDesc":"FRD", "SubCatDesc":"BBC"}
]

Need to get the output of distinct values based on both CategoryDesc and SubCatDesc like:

[ { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"}
  { "CategoryDesc": "FRD" ,"SubCatDesc":"VRD"}
  { "CategoryDesc":"FRD", "SubCatDesc":"BBC"}
]

How Can we Achieve this.? Can someone help on this

CodePudding user response:

You can do it something like

const array = 
[
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"},
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"},
   { "CategoryDesc": "FRD" ,"SubCatDesc":"VRD"},
   { "CategoryDesc": "FRD" ,"SubCatDesc":"VRD"},
   { "CategoryDesc":"SEC Violations (Insider Trading, Securities Fraud)", "SubCatDesc":"BBC"},
   { "CategoryDesc":"FRD", "SubCatDesc":"BBC"}
]

let result=array.filter((a,i)=> array.findIndex(s=> s.CategoryDesc == a.CategoryDesc && s.SubCatDesc ==a.SubCatDesc) ===i)

console.log(result);

  • Related