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?
You can check the array using foreach and then pop the item if it exists otherwise add new item...
sample newItemValue &submitFields are key,value pairs
Use a js library like underscore.js for these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.
Short example:
You can use jQuery grep and push if no results: http://api.jquery.com/jQuery.grep/
It's basically the same solution as in the "extending the prototype" solution, but without extending (or polluting) the prototype.