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
Given Object array (or store)
var storeWithDup = [{category: "Cat A"}, {category: "Cat B"}, {category: "Cat A"}];
var storeWithoutDup = [{category: "Cat A"}, {category: "Cat B"}, {category: "Cat C"}];
1. Sort Object array using custom comparison function
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;
}
}
};
2. Check for duplicate adjacent elements in an array
var arrayDuplicateChecker = function(inpArray){
for(var i = 1; i < inpArray.length; i++){
if(inpArray[i-1].category == inpArray[i].category){
return true;
}
}
return false;
};
3. Helper function to check for duplicate categories in a store
var checkForDuplicateCat = function(inpStore){
// 1. Sort array
inpStore.sort(myComparator);
// 2. check for adjacent duplicates
return arrayDuplicateChecker(inpStore);
};
Result
alert(checkForDuplicateCat(storeWithDup)); // True
alert(checkForDuplicateCat(storeWithoutDup)); // False
Link to JS Fiddle: Object array sort and comparator