views:

315

answers:

2

How can i push up into an array if neither values exist? Here is my json array/object:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

If i tried to push again into the array with either name: "tom" or text: "tasty" i dont want anything to happen... but if neither of those are there then i want it to .push()

How can i do this?

+5  A: 

You could extend the Array prototype with a custom method:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

var array = [{ name: "tom", text: "tasty" }]
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});
Darin Dimitrov
I think your camparer (comparator?) should take two arguments, this would simplify the case when the added value is inline and not in a variable you can access in your function.array.pushIfNotExist({ name: "tom", text: "tasty" }, function(a,b){ return a.name === b.name });
Vincent Robert
A: 

Use a dictionary (hash/tree) instead of an array.

trinithis
Are all these available in javascript?
rahul
Yes: http://code.google.com/p/jshashtable
Tim Down