-1

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.

Bekki
  • 719
  • 2
  • 12
  • 20
  • 1
    possible duplicate of [Determine whether an array contains a value](http://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) – iamawebgeek Jul 08 '15 at 12:48
  • 1
    `indexOf` has known issues in IE8. You are using jQuery so it is safe to use `jQuery.inArray()` – rrk Jul 08 '15 at 12:56

5 Answers5

3

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;
}
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
3

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>
Alex Char
  • 32,879
  • 9
  • 49
  • 70
1

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')
}
hsz
  • 148,279
  • 62
  • 259
  • 315
0

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');
Nikhil Batra
  • 3,118
  • 14
  • 19
0

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.

DEMO

$(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);
});
Hemal
  • 3,682
  • 1
  • 23
  • 54