We can use JavaScript to add an item to an array if it does not already exist in the array by making use of the indexOf() and push() methods.
var someArray = ["a","b","c"];
if( someArray.indexOf("d") == -1 ){
someArray.push("d");
}
console.log(someArray);
#Output
['a', 'b', 'c', 'd']
In the code above, we simply have an if-else conditional statement that checks whether the item is in the array using the indexOf() method. If the item is not in the array, then the number -1 will be returned. And if that is the case, we can then use the push() method to add the new item to the array.
Let’s put this code in a function to make things simpler.
function addItem(arr,item){
if( arr.indexOf(item) == -1 ){
someArray.push(item);
}
};
In our function above, the user simply needs to give the function the array they want to check, and the item they want to add if it does not exist.
Now let’s test this function out.
function addItem(arr,item){
if( arr.indexOf(item) == -1 ){
someArray.push(item);
}
};
var someArray = ["a","b","c","hello",3,false];
addItem(someArray,"d");
addItem(someArray,"3");
addItem(someArray,"b");
addItem(someArray,"Hello");
addItem(someArray,"false");
console.log(someArray);
#Output
['a', 'b', 'c', 'hello', 3, false, 'd', '3', 'Hello', 'false']
Remember that with the indexOf() method, characters are case-sensitive. So you will notice that in the example above, “Hello” was added to our array even though “hello” was already in it.
Adding Items From One Array to Another if They Do Not Exist
In this example, we will simply have an array of colors that we want to add to another array of colors, and only add the color if it does not exist. To do this we can use our code from above and simply add a for loop.
Here is the JavaScript code to do this:
var array1 = ["black","red","blue","green","yellow","pink","orange","brown","white","purple"];
var array2 = ["blue","green","yellow","red","teal"];
for( var i = 0; i<array1.length; i++ ){
if( array2.indexOf(array1[i]) == -1 ){
array2.push(array1[i]);
}
};
console.log(array2);
#Output
['blue', 'green', 'yellow', 'red', 'teal', 'black', 'pink', 'orange', 'brown', 'white', 'purple']
Hopefully this article has been useful in helping you understand how to use JavaScript to add an item to an array if the item not exist.
Leave a Reply