Jack
Jack

Reputation: 13

How to get Distinct Values based on two attributes

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

Upvotes: 0

Views: 52

Answers (1)

jitender
jitender

Reputation: 10429

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);

Upvotes: 1

Related Questions