Accueil / Informatique / Data Structures / Checking existence of an element in an array with JavaScript
Checking existence of an element in an array with JavaScript
Checking existence of an element in an array with JavaScript

Checking existence of an element in an array with JavaScript

Print Friendly, PDF & Email

JavaScript is a loosely typed or a dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and reassigned) values of all types. In other words, everything in JavaScript is Object in which we can use it to declare any collection typed data structure like in statically typed languages such as Array, Dictionary, Map, Set, etc. In this post, I want to address how to check whether an element exists in the array, dictionary, map or not.

Read more Data Structures in JavaScript

This is the documentation maintained by one of the oldest JavaScript alliances called Mozilla who is the founder of Netscape.

Traditional approaches

Don’t let you waste your valuable time any more. Let’s give an example:

let charts = {
  curationstate: "Curation State",
  modellingapproach: "Modelling Approach",
  organism: "Organism",
  journal: "Journal"
};

Now, to check whether charts["curationstate"] exists or not, we can do as below

// Note: the three equal signs so that null won't be equal to undefined
if (charts["curationstate"] === undefined) {
   // do something
}

where undefined is a special constant value in JavaScript. This is probably the best way to check an element exists or not in a collection. The logical expression will return true if the key in question does exist, otherwise it will return false. Now, take a look at another example with array.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits instanceof Array); // the output: true
console.log(fruits[0] === undefined); // the output: false

However, you might need to check the existence of a specific key rather getting the whole actual value of that element. In other words, it’s theoretically possible to check missing keys by using in operator. Let’s look at the example below.

// this works even if you have {"publication": undefined}
if ("publication" in charts) {
   // do something
}

The former is considered the most commonly used method while the latter is presented in this post as the sake of the completeness.

Modern approaches

I used to work with an awful lot of data often organised in arrays, dictionaries or maps. Therefore, looking for an effective and convenient way of checking the existence of an element in these data structures is valuable. I guess most JavaScript developers likely accept this solution.

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } //and so on goes array... 
];
if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  /* vendors contains the element we're looking for */
}
// or, better yet:

if (vendors.some(e => e.Name === 'Magenic')) {
  /* vendors contains the element we're looking for */
}
// EDIT: If you need compatibility with lousy browsers then your best bet is:
if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  /* vendors contains the element we're looking for */
}

Hopefully, this offers some additional tips/tricks and/or insights into how to check an element existing or not in a dictionary or an array in JavaScript/jQuery, and how to make it fit into your need. Happy coding!

All constructive comments are welcomed. If you are willing to contribute financial support for our website, please follow the instructions below.

À propos Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

Laisser une réponse

Votre adresse email ne sera pas publiéeLes champs requis sont surlignés *

*

*

code

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.