0

I'm trying to create an Array with unique objects. I've got json data from a tounament that I want to order by pools. Each match got his own pooldata so he will push the pool data of each match to the array. This will create an Array of 5 of the same pool values. This is my code:

var arr = [];
for (var i = 0; i < data.objects.length; i++){
    obj = {
        poolId: data.objects[i].pool.id,
        poolLetter: data.objects[i].pool.name
    };

    if (arr.indexOf(obj) == -1) {
        arr.push(obj); 
    }else{} 
}
1
  • If you're creating a new obj in every loop turn with that object literal, the particular instance will never be an element of the array. indexOf uses ===, which compares objects by identity, not by (custom) equivalence! Commented Oct 25, 2013 at 12:23

4 Answers 4

1

The problem is that the obj you are generating in the loop is not going to be the same object inside your arr array, they will have different signatures, so you can't use indexOf in this instance.

Instead, you will have to loop over the arr array to see if you can find any elements with the same poolId or poolLetter:

var arr = [];
for (var i = 0; i < data.objects.length; i++){
    obj = {
        poolId: data.objects[i].pool.id,
        poolLetter: data.objects[i].pool.name
    };

    // Do the insert if arr doesn't already contain this poolId    
    if(!arrayContains(arr, obj.poolId)) arr.push(obj);
}

// Helper function to find an instance of poolId in the given array
function arrayContains(arr, poolId) {
    for(var x = 0; x < arr.length; x++) {
        if(arr[x].poolId === poolId) {
            return true;
        }
    }
    return false;
}

Here is a fiddle which demonstrates the above.

Sign up to request clarification or add additional context in comments.

Comments

0

indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

then

var obj1 = { a:1};

var obj2 = { a:1};

obj1 === obj2; // wrong

when you write "var obj1={a:1}" ,javascript create a new object.

Comments

0

You can use Array Prototype. Just pass the object.

Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
    if (this[i] === obj) {
        return true;
    }
}
return false;
}

Use the following

alert([1, 2, 3].contains(2)); //true
alert([1, 2, 3].contains('2')); //false

Comments

0

There is also a jQuery solution. I know you didn't asked for a jQuery answer. But maybe you want use it.

jQuery.inArray() returns the index of a specified value and returns -1 if not found.

http://api.jquery.com/jQuery.inArray/

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.