Javascript program to validate if the user input matches a single value in an array

Currently, I am working with an array:

var something = ["1","2","3","4"] ;

My plan is to prompt the user to select a number. If the chosen number matches any value in the array, I want to trigger a specific action.

Here's my dilemma: How can I verify if the user's input matches any value within the array?

if(something === "input"){
    console.log("Good choice!");
} 

Obviously, the current if statement I have won't work. How can I make it check each value in the array to see if there is a match?

It would be fantastic if someone could assist me with this issue! ;)

Thanks in advance!

Answer №1

One useful feature of arrays in JavaScript is the presence of the indexOf method. This method returns the index of a specified argument within the array, or -1 if the argument is not found:

if (arr.indexOf(element) > -1) {
    // Element found in the array!
}

It's important to note that some older web browsers do not support this method, but a polyfill is available in the linked MDN article for compatibility.

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

storing a value in the browser's local storage

I am in the process of creating a new game that includes a high score feature. The idea is that when the current score surpasses the existing one stored locally, it will be replaced: localStorage.setItem('highScore', highScore); var HighScore = ...

How can I randomly choose 5 TR items and show them to the user?

How can I randomly select and display 5 questions for the user? The rest of the questions should be hidden on the page and only 5 questions should be displayed. This is a sample code. I want the user to see 5 questions out of many questions when the page ...

Tips on disregarding events within an html table

I have a see-through table with a width set to 100% that houses various HTML content. I am utilizing the table to properly center a particular element on the screen. However, the table is intercepting mouse events and preventing users from clicking on lin ...

What is the reason behind Java's decision to support arrays of arrays instead of multidimensional arrays?

Can you explain the variations between multidimensional arrays and array-of-arrays? What is the rationale behind Java endorsing arrays of arrays, as opposed to multidimensional arrays ? ...

Trouble locating Angular module while referencing script as an ES6 module

Check out this simple plunk here. My goal is to reference the app.js file as an ES6 module by setting the type attribute of the script tag to module. However, when I add the type attribute, Angular is unable to find the module. If I remove it, then it work ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

Transmitting information through socket.emit from the client to the server

I'm facing an issue while trying to send numeric data from the client to the server using socket.emit. The problem is that the server doesn't seem to be receiving any data, as only `null` gets logged or I might be doing something wrong in my appr ...

What is the best way to extract the singular PDF link from a webpage?

Currently, I am attempting to utilize Selenium in Java to access DOM elements. However, I have encountered an issue while testing the code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is n ...

Utilizing and interpreting the input data provided by the user in jQuery

While following the tutorial at , I am trying to extract specific parameters from the user input to generate a corresponding URL. Below is the code snippet I am working with: <html> <head> <title>USGS Earthquake Feed</title> ...

Easily done! Using JavaScript to generate a blinking cursor on a table

Working on a project to develop a dynamic version of the classic game Tic-Tac-Toe... However... Every table cell is displaying an irritating flashing cursor, almost like it's behaving as an input field. Any insights into why this is happening...? O ...

Learn how to execute shell commands on a Linux server from a Node.js application by utilizing Socket.io for establishing a connection. This includes tasks such as running "ls -ltr", changing

After successfully establishing a connection with my Linux server, I aim to execute shell commands for automation purposes such as changing directories and creating new folders. The main objective is to connect to the Linux server through a webpage, wher ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

Ember Gain a comprehensive understanding of the flow of execution between route and controller

Below is a snippet of my "box" route/controller: export default Ember.Controller.extend({ initialized: false, type: 'P', status: 'done', layouts: null, toggleFltr: null, gridVals: Ember.computed.alias('mode ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

Error: The $http variable in Vue Resource is not defined

I encountered an issue with the following code snippet inside my ready method: this.$http.get('url',{},{ headers: { "X-App-Token": "token" } }).then( (data) => this.$set('cdata',data.data)) ...

Retrieval of jQuery remove() method

Essentially, I am utilizing an OnClick function to delete a DIV. Once the OnClick is triggered, it invokes the remove() jQuery function to eliminate the div. Below is my code that implements the removal using remove(): <div id="add"> <button typ ...

Create a button toggle feature to dynamically display data for a specific record within an ng-repeat loop

Currently, I am facing an issue while implementing a start and stop timer in JavaScript for a list of records. To display all the items, I am using ng-repeat. Each repeated element has a Start/Stop toggle button. The problem arises when there are 4 records ...

Locate a particular word in every element within an array range (angularjs)

I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner. Currently, I am working on creating a poll app using angular. In my project, I have an array scope named items, which holds all the items to be adde ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...