0

I have a collection of objects

var array = 
[
    {"category":"A", "categoryname":"somename", key: 1, description: "something"}, 
    {"category":"A", "categoryname":"somename", key: 1, description: "something"}, 
    {"category":"B", "categoryname": "somename", key: 1, description: "something"}
    {"category":"B", "categoryname": "somename", key: 3, description: "something"}
    {"category":"C", "categoryname": "somename", key: 2, description: "something"}
    {"category":"C", "categoryname": "somename", key: 2, description: "something"}
]

that have 4 values (category, categoryname, key, description) and I need to loop through it and get a unique list of objects based on the category. But I want to return the unique list with 2 preoperties and not just one. If I use

_.uniq(_.pluck(array,"category"))

this gives me what I want except I need the categoryname as well as the category. Is this possible?

chuckd
  • 13,460
  • 29
  • 152
  • 331

2 Answers2

2

There are a couple of questions on the same use case already.

Plucking Multiple Properties

Removing duplicate objects with Underscore for Javascript

Community
  • 1
  • 1
Sreekanth
  • 3,110
  • 10
  • 22
-1

You can use $.unique(), Array.prototype.map(), JSON.stringify(), JSON.parse()

var array = [{
  "category": "A",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "A",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "B",
  "categoryname": "somename",
  key: 1,
  description: "something"
}, {
  "category": "B",
  "categoryname": "somename",
  key: 3,
  description: "something"
}, {
  "category": "C",
  "categoryname": "somename",
  key: 2,
  description: "something"
}, {
  "category": "C",
  "categoryname": "somename",
  key: 2,
  description: "something"
}];

var res = $.unique(array.map(function(el) {
  return JSON.stringify([el.category, el.categoryname])
})).map(JSON.parse);

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
guest271314
  • 1
  • 15
  • 104
  • 177