How do I add an element in to an array if it is not already in the array?
var fruits = ["Banana", "Orange", "Apple", "Mango"];
I read that push() could be used to add items but I'm not sure how to check if an item is already in the array.
How do I add an element in to an array if it is not already in the array?
var fruits = ["Banana", "Orange", "Apple", "Mango"];
I read that push() could be used to add items but I'm not sure how to check if an item is already in the array.
Like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
if (fruits.indexOf('coconut') === -1) {
fruits.push('coconut');
}
This will check if "coconut" is in the array, if it's not then indexOf
will return -1
, which will cause the if statement to run. Therefore pushing "coconut" into the array.
-1
means "not found".
To check if an item is in an array, just do:
if (fruits.indexOf('coconut')) {
return false;
}
You can use jquery .inArray()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//check if is already in the array
if (jQuery.inArray("Banana", fruits) === -1) {
fruits.push("Banana");
}
console.log(fruits);//prints out ["Banana", "Orange", "Apple", "Mango"]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
With indexOf
method you can check the position of the given element in the array. If -1
is returned, it's not in the array.
if (fruits.indexOf('New item') === -1) {
fruits.push('New item')
}
indexOf()
searches for a particular element in the array and returns -1 if element is not present.
Then after checking that you can put the element in array using push()
if(fruits.indexOf('element to be added') === -1)
fruits.push('element to be added');
First you should check if item to enter exists or not.
For that use .indexOf()
function.
If not, use .push()
to add a new item.
$(document).ready(function(){
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var item_to_enter="Grapes";
var item_should_not_enter="Apple";
if(fruits.indexOf(item_to_enter)<0)
{
fruits.push(item_to_enter);
}
if(fruits.indexOf(item_should_not_enter)<0)
{
fruits.push(item_should_not_enter);
}
console.log(fruits);
});