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?
It is quite easy to do using the
Array.findIndex
function, which takes a function as an argument:I used map and reduce to do this in the case where you wish to search by the a specific property of an object, useful as doing direct object equality will often fail.
You can use the findIndex method with a callback function and its "this" parameter.
Note: old browsers don't know findIndex but a polyfill is available.
Sample code (take care that in the original question, a new object is pushed only if neither of its data is in previoulsy pushed objects):
Not sure about speed, but
stringification
+indexOf
is a simple approach. Start with turning your array into a string:Then for a series of attribute-value pairs you can use:
Finding a whole object is simpler:
In case anyone has less complicated requirements, here is my adaptation of the answer for a simple string array:
Update: Replaced indexOf and trim with jQuery alternatives for IE8 compatability
For an array of strings (but not an array of objects), you can check if an item exists by calling
.indexOf()
and if it doesn't then just push the item into the array: