JQuery Remove Element From Array If Exists

jquery , JavaScript




Hi Guys,

Today, I will show you how to check remove element from array if exists. If the value does not exists in array, then it should be added into the array, if the value already exists, it should be deleted.

You can use indexOf() method to check a given value or element exists or not. This method is return the index of the element inside the array.

Second solution in includes() method used check given array value or element exists or not But this method returns only true or false instead of index nmber, as you can see here:

I give you two solution for JQuery Remove Element From Array If Exists. Its solution as bellow.

Solution 1


var colors = ["green", "pink", "white", "black", "orange"];

// Check if a value exists in the colors array

if(colors.indexOf("pink") !== -1){

alert("Value exists!")

} else{

alert("Value does not exists!")



Solution 2


var colors = ["green", "pink", "white", "black", "orange"];

alert(colors.includes("pink")); // Outputs: true

alert(colors.includes("red")); // Outputs: false

alert(colors.includes("orange")); // Outputs: true

alert(colors.includes("purple")); // Outputs: false


It will help you...

Recommended Posts