Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a given string is already present in an array or list in JavaScript? [duplicate]

Tags:

javascript

Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?

I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?

like image 259
Ant's Avatar asked Mar 09 '11 12:03

Ant's


People also ask

How do you check if a string already exists in an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if a value is already present in an array?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How do you check if there is a duplicate in array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.


2 Answers

In javascript you have Arrays (lists) and Objects (maps).

The literal versions of them look like this:

var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object

if you which to figure out if a value exists in an array, just loop over it:

for(var i=0,len=mylist.length;i<len;i++) {
  if(mylist[i] == 2) {
     //2 exists
     break;
   }
}

if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:

if(mymap.seats !== undefined) {
  //the key 'seats' exists in the object
}

if(mymap.seats == 2) {
  //the key 'seats' exists in the object and has the value 2
}
like image 194
Martin Jespersen Avatar answered Sep 23 '22 17:09

Martin Jespersen


Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

like image 34
CloudyMarble Avatar answered Sep 23 '22 17:09

CloudyMarble