Reputation: 4234
I have this array:
[{category:'Cat A'}, {category:'Cat B'},{category:'Cat A }]
I want a function that returns true if two or several keys (category) is the same in the array.
Is there any smart way to do this with underscore? Can't find any in the docs. Or do I need to this manually with loops?
Upvotes: 0
Views: 88
Reputation:
My, how complicated we make things.
var array = [{category: 'Cat A'}, {category: 'Cat B'}, {category: 'Cat A }],
groups = _.groupBy(array, 'category');
duplicated = Object.keys(groups).filter(function(cat) {
return groups[cat].length>1;
});
console.log(duplicated);
Upvotes: 0
Reputation: 6613
As a new JS programmer, I wanted to solve this problem using only JS. Here is my attempt, please suggest if I'm missing something over here
var storeWithDup = [{category: "Cat A"}, {category: "Cat B"}, {category: "Cat A"}];
var storeWithoutDup = [{category: "Cat A"}, {category: "Cat B"}, {category: "Cat C"}];
var myComparator = function(value1, value2){
if(value1.hasOwnProperty("category") &&
value2.hasOwnProperty("category")){
if(value1.category < value2.category){
return -1;
} else if(value1.category > value2.category){
return 1;
} else {
return 0;
}
}
};
var arrayDuplicateChecker = function(inpArray){
for(var i = 1; i < inpArray.length; i++){
if(inpArray[i-1].category == inpArray[i].category){
return true;
}
}
return false;
};
var checkForDuplicateCat = function(inpStore){
// 1. Sort array
inpStore.sort(myComparator);
// 2. check for adjacent duplicates
return arrayDuplicateChecker(inpStore);
};
alert(checkForDuplicateCat(storeWithDup)); // True
alert(checkForDuplicateCat(storeWithoutDup)); // False
Link to JS Fiddle: Object array sort and comparator
Upvotes: 0