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?
To push an element in an array if it doesn't exist, use the includes() method to check if the value exists in the array, and push the element if it's not already present. The includes() method returns true if the element is contained in the array and false otherwise. Copied!
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
ES6 - Array Method push()push() method appends the given element(s) in the last of the array and returns the length of the new array.
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:
var newItem = "NEW_ITEM_TO_ARRAY"; var array = ["OLD_ITEM_1", "OLD_ITEM_2"]; array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists"); console.log(array)
It is quite easy to do using the Array.findIndex
function, which takes a function as an argument:
var arrayObj = [{name:"bull", text: "sour"}, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" } ] var index = arrayObj.findIndex(x => x.name=="bob"); // here you can check specific property for an object whether it exist in your array or not index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With