Locate an item within a JavaScript array

Similar Question:
Javascript - Checking for value in array

Can you spot the issue here?

var zipCodes =(['90001','90002','90003']);

Determine if a specific value is present in the array zipCodes

if('90001' in zipCodes) {
  alert('True');
};

Answer №1

When using the in operator, it examines property names rather than values.

Since it's dealing with an Array, the property names will correspond to the indices of the Array.

In a modern environment, you have the option to utilize Array.prototype.indexOf().

if(zipCodes.indexOf('90001') > -1) {

If your target includes environments lacking support for .indexOf(), you can incorporate the MDN fix.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";

        if (this === void 0 || this === null) throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) return -1;

        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) // shortcut for verifying if it's NaN
            n = 0;
            else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }

        if (n >= len) return -1;

        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) return k;
        }
        return -1;
    };
}

Answer №2

To determine if a specific value is present in an array, you can utilize the indexOf method to search for the position of the item within the array. If the item is not found in the array, a -1 will be returned:

let zipCodes =(['90001','90002','90003']);
zipCodes.indexOf('90001') // 0
zipCodes.indexOf('90002') // 1
zipCodes.indexOf('90003') // 2
zipCodes.indexOf('90004') // -1

if(zipCodes.indexOf('90001') != -1) {
  alert('True');
};

For more information, visit

Answer №3

Consider using an object instead of an array for better efficiency. If all you need is to perform a lookup, objects are a more suitable choice.

var zipCodes = {"90001": true, "90002": true, "90003": true};

if ('90001' in zipCodes) {
    alert('True');
}

Check out this jsfiddle link to see it in action: http://jsfiddle.net/jfriend00/ZNGTq/

Answer №4

If you're looking for a solution, consider implementing code similar to the following:

var zipCodes =(['90001','90002','90003']);

if (zipCodes.has('90001')) {
  ....
}

    Array.prototype.has=function(v){
        for (i=0;i<this.length;i++){
           if (this[i]==v) return i;
        }
        return false;
    }

For more detailed information, refer to this resource:

....

Answer №5

When using the in operator, it is important to understand that it checks for a specific property within an object. If you are looking to convert this functionality for use with arrays, check out this informative article on how to test for a value within a JavaScript array: Testing Value in JavaScript Array

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging ngIf and ngFor within choice

Is there a way to combine ngIf and ngFor in a single line of code? Here is the code snippet I am currently using: <option *ngIf="tmpLanguage.id!=languages.id" *ngFor="let tmpLanguage of languages" [ngValue]="tmpLanguage.id"> {{tmpLang ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

Encoding URLs with PHP and JavaScript for enhanced security

I am currently working with a HTML text that was encoded in PHP using the urlencode function. Now, I need to decode this text in JavaScript. However, when I use the unescape function in JavaScript, all special characters are reverting back except for spa ...

Unauthenticated user attempting to send a post request via React JS without proper authentication

Currently, I am working on a project where I am following a video tutorial that demonstrates how to authenticate a user using node and passport JS. The tutorial itself uses Hogan JS as its view engine, but I have decided to implement React as my front end ...

Ways to conceal submenu when clicking away from the navigation bar

I am looking to create a directive that will generate a navigation bar. Check out my code on JSFiddle here. Here is the code snippet from index.html : <html lang="fr" ng-app="activity" id="ng-app"> <div ng-controller="mainCtrl"> ...

What is the proper usage of a jwt token?

I'm completely new to this and I've dedicated all my time to figuring out how to create a mechanism for generating JWT tokens. These tokens are necessary for identifying the 'signed in' status of users. I opted for FastAPI, and after s ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

execute a synchronous function within a promise

Recently diving into the world of JavaScript and asynchronous operations, I found myself working on a Node.js router with Express that pulls weather data from MongoDB using Mongoose. This data is collected from various sites at 15-minute intervals and proc ...

What is causing my HTML to not recognize my Angular JS code?

Trying to dive into Angular JS, I wrote a small piece of code but for some reason, the HTML is not recognizing Angular JS. This is my index.html file: <!DOCTYPE HTML> <html ng-app="store"> <head> <link rel="stylesheet" type=" ...

Struggling with a TypeORM issue while attempting to generate a migration via the Command Line

Having some trouble using the TypeORM CLI to generate a migration. I followed the instructions, but when I run yarn run typeorm migration:generate, an error pops up: $ typeorm-ts-node-commonjs migration:generate /usr/bin/env: ‘node --require ts-node/regi ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Is the value of useState not updating even after setting it in a callback function?

I am facing an issue where the error message is not being added to the error state when an error occurs. The backend sends the error message in JSON format { "error": "error message" }, and even though I can log this error message successfully, the error ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

Using several autocomplete-light dropdown menus in a Django template

I am in the process of creating a web application that necessitates searching for a specific user record by inputting either the first name OR last name. While two more search attributes will be added in the future, I am currently facing issues with incorp ...

What is the best way to manage a promise's response?

I'm currently facing a situation where I need to create a petition to an endpoint and retrieve the URL of the backend that I intend to use. My setup involves a file with the API configuration where I instantiate axios. Previously, my approach was sim ...

Ways to organize the information within the Ul and Li elements

I need help sorting the data within <ul> and <li> elements using jQuery. Below is a snippet of my code: <ul id="rootUl"> <li> <div id='title'>MSFT</div> <div id='price'>230</d ...

Explore ways to incorporate special symbols in a jQuery array

I'm looking to include special characters in a jQuery array. I'm not quite sure how to do this. Currently, my code is: $scope.categories = ['Red', 'White', 'Rose', 'Sparkling']; and I would like it to be: ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Remove the </div> text and replace it with nothing

I'm attempting to substitute the end tag div with an empty string. Here is my code: $('#textDiv').html().replace(/'</div>'/g,'').replace(/<div>/g,'\n') This is the HTML: <div id='tex ...