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 ?

user3469203
  • 537
  • 1
  • 9
  • 22

1 Answers1

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]);
        }
    });
Community
  • 1
  • 1
blgt
  • 8,135
  • 1
  • 25
  • 28