How can I push into an array if neither values exist? Here is my array:
[
{ 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 don't want anything to happen... but if neither of those are there then I want it to .push()
How can I do this?
Like this?
With object
In case you need something simple without wanting to extend the Array prototype:
This is working func for an objects comparison. In some cases you might have lot of fields to compare. Simply loop the array and call this function with a existing items and new item.
You could extend the Array prototype with a custom method:
http://api.jquery.com/jQuery.unique/
you might be interested in makeArray too
The previous example is best in saying that check if it exists before pushing. I see in hindsight it also states you can declare it as part of the prototype (I guess that's aka Class Extension), so no big enhancement below.
Except I'm not sure if indexOf is a faster route then inArray? probably.
I know this is a very old question, but if you're using ES6 you can use a very small version:
Very easy, at first add a filter which removes the item - if it already exists, and then add it via a concat.
Here is a more realistic example:
If you're array contains objects you could adapt the filter function like this: