Trying to determine if an array holds a specific value? (I've experimented with a few methods, but I'm not quite sure yet)

Being relatively new to JavaScript (I've been studying for about a week), I am facing a challenge in figuring out how to determine if an array contains a specific string. Here, you can find the word-guessing game that I created.

The 'contains' function is defined like this:

function contains(word, list){
  if(word in list){
    return true;
  }
  else {
    return false;
  }
};

Despite my efforts, I always end up with a false value and I'm not sure what I'm missing.

I attempted to implement both the third technique mentioned here and the recommended technique illustrated here, but encountered the same issue.

If anyone could provide some assistance, it would be greatly appreciated!

Answer №1

In order to clarify, a separate answer is being provided here. The proper method to check if an element is in an array:

var myArr = ['oranges', 'grapes', 'kiwis'];

if (myArr.indexOf('kiwis') > -1) { // myArr.indexOf('kiwis') will return 2
    console.log('we have kiwis'); // this will be displayed
}

if (myArr.indexOf('watermelon') > -1) { // since it's not in the array, it will be -1
    console.log('no watermelon!'); // this will not display
}

It's worth mentioning that for...in loop is not suited for iterating over arrays as it is primarily used to iterate over object keys. When it comes to iterating over arrays in JavaScript, using a traditional for loop is the recommended approach.

Answer №2

To determine the index of a particular element in an array, you can utilize the indexOf method.
Keep in mind that the in operator is used to check for keys, not values within objects.
Alternatively, you can iterate through all object keys using a for..in loop:

for (key in object)
    console.log(object[key])

In the context of arrays, a similar outcome could be achieved with the following approach:

for (index=0; index<array.length; index++)
    console.log(array[i])

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

What is the best method for creating clean views using AngularJS UI-Router?

Hello! My latest project is this app I've created: var accolade = angular.module('accolade', [ 'ui.router', 'personControllers', 'personFactories' ]); accolade.config(['$stateProvider', ...

My objective is to modify a JSON object based on the chosen value from a dropdown menu

Here is the code snippet I have created using HTML: <select style="width:100px;" data-nodrag ng-model="conditions" ng-change="changingCondition(this)"> <option value="and">and</option> <option value="or">or</option> & ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

Ways to conceal a dynamically generated div upon page load?

I am currently facing a scenario where I need to dynamically create a div. My initial approach was to create it on the document ready event, but the requirement is for it to be displayed only upon selection. The problem I am encountering is that the empty ...

The mdSidenav service encounters difficulties locating a component within an Angular component

Trying to understand why an Angular .component(), which contains a <md-sidenav> directive, cannot be located from the component's controller. Angular throws the error message: No instance found for handle menu The complete component code is ...

What is the best way to identify the specific button that has been clicked among a group of identical buttons in the given code snippet?

I am currently working on integrating a voting system for comments that allows users to upvote or downvote. To achieve this, I have added two buttons to each comment. With the help of jQuery's each() and click() functions, I am aiming to identify the ...

Highlight the active page or section dynamically using HTML and jQuery - How can it be achieved?

What am I trying to achieve? I am attempting to use jQuery to dynamically highlight the current page from the navigation bar. Am I new to jQuery/HTML? Yes, please excuse my lack of experience in this area. Have I exhausted all resources looking for a sol ...

Unable to invoke a function within a JavaScript class

As I develop a THREE.js graphics program, I am looking to create a BodyPart class in Javascript that includes various methods. However, I have encountered an issue where I am unable to successfully call these methods. Despite the code displaying 'call ...

Transitioning from AngularJS to Angular: Updating the factory prototype

I've been in the process of migrating from AngularJS to Angular and have made a lot of progress. However, I am currently facing challenges with factories and prototypes. In this context, the Card object represents a playing card. function Car ...

Incorporate a Vue component into a string for seamless integration with Buefy's confirmation feature

Can a vue component be loaded into a string for use with buefy confirm? I attempted the following approach, but it did not work as expected: archiveChannelPrompt () { const archiveChannel = document.createElement('template'); new Vue({ ...

The integration of Material-UI Autocomplete and TextField causes google autocomplete to activate

I am currently working on integrating the Autocomplete component into my project. However, I am facing an issue where the browser's autofill/autocomplete feature kicks in after some time. Is there a way to disable this behavior? ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

Function to handle click events on Highcharts column series points

Just recently, I posted a query regarding Highcharts column charts drilldown. I have discovered that within the click event of the point object, you can determine which column was clicked. I have integrated this functionality into my code, but unfortunatel ...

In IE8, scrolling a child div causes the entire page to scroll

I noticed that when a div with a scrollbar reaches its end, the page begins to scroll. While this is a default behavior for most browsers, I want to prevent the page from scrolling once the div has reached its end. I have come up with a solution and create ...

Glitch in the scroll glue directive

Currently, I'm attempting to incorporate scroll-glue in order to automatically scroll to the bottom of a message.html page. My approach involved including the directive 'luegg.directives' in the following manner. (function(){ 'use stri ...

Issues with jQuery autocomplete when using special characters (Norwegian)

On my website in Norway, I am facing an issue with jQuery's autocomplete function. When users type in the Norwegian characters æ, ø, and å, the autocomplete feature suggests words with these characters within them but not ones that start with these ...

Is there a way to retrieve the data attribute value from a button that has been clicked?

Is there a way to retrieve the data attribute value of a clicked button? I need this information for handling an ajax form submission. Any suggestions on how to achieve that? Here is an example of my button (there are multiple buttons corresponding to dif ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

Filtering results in PostgreSQL by an array column

I have a function that generates a table. One of the columns consists of text arrays with a maximum of two elements. Occasionally, duplicate rows are returned with the elements in reverse order. I am looking for a solution to filter out these duplicates an ...

Which core modules of Node Js serve as the foundation for Express Js?

Which core modules of Node.Js are utilized in the construction of the Express Js Framework? Besides the 'http' and 'fs' modules, what other modules does Express Js integrate? ...