Array.push() if does not exist? Array.push() if does not exist? arrays arrays

Array.push() if does not exist?


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)