Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.push() if does not exist?

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 image 686
tarnfeld Avatar asked Jan 01 '10 10:01

tarnfeld


People also ask

How do you avoid adding to an array if element already exists?

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!

How do you check if a value does not exist in an array JavaScript?

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.

What does push () method in array?

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Is array push ES6?

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.


2 Answers

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)
like image 136
Jiří Zahálka Avatar answered Sep 22 '22 12:09

Jiří Zahálka


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")   
like image 41
Ashish Yadav Avatar answered Sep 20 '22 12:09

Ashish Yadav