0

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?

3 Answers 3

1

You can try the uniq function:

var arrayUniq = _.uniq(myArray, function(item) { return item.category; });
var isUniq = arrayUniq.length === myArray.length
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.