Joe
Joe

Reputation: 4234

Check if object attribute in an array is unique

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

Answers (3)

user663031
user663031

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

Rohit
Rohit

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

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

Upvotes: 0

Adriien M
Adriien M

Reputation: 1185

You can try the uniq function:

var arrayUniq = _.uniq(myArray, function(item) { return item.category; });
var isUniq = arrayUniq.length === myArray.length

Upvotes: 1

Related Questions