0

I got a jquery function :

$.extend({
    distinct : function(anArray) {
        var result = [];
        $.each(anArray, function(i,v){
            if ($.inArray([v.key, v.value], result) == -1) result.push([v.key, v.value]);
        });
        return result;
    }
});

I want to get unique [key,value] on the anArray array.

But the $.inArray([v.key, v.value], result) always returns -1, so at the end I always have all the values in result array.

What's wrong ?

4
  • 1
    What is example input and what is expected output? Commented Jul 9, 2014 at 9:52
  • So anArray is an array of objects? Commented Jul 9, 2014 at 9:55
  • Yes anArray is an object with some values, like key and value. Commented Jul 9, 2014 at 10:08
  • in result I just want unique [key,value] Commented Jul 9, 2014 at 10:09

1 Answer 1

1

The issue is object comparison. See this question for more details: How to determine equality for two JavaScript objects?

In javascript, comparing arrays for equality compares their references, not their contents (same as with objects); thus:

[1] == [1]; // false

You need to do a custom comparison for both key and value, rather than using $.inArray:

    $.each(anArray, function(i,v){
        var present = false;
        for(var j in result) {
            if (v.key === result[j][0] && v.value === result[j][1]) {
                present = true;
                break;
            }
        }
        if(!present) {
            result.push([v.key, v.value]);
        }
    });
Sign up to request clarification or add additional context in comments.

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.