Evaluating numerous array elements within an if statement

For my simple tic tac toe game, I am currently checking for various win states. The game board is stored in an array, and to check for a win with the top three spaces, I am using the following logic:

if (tableArr[0].hasClass('userTaken') && tableArr[1].hasClass('userTaken') && tableArr[2].hasClass('userTaken')){
    select(); //ends game
}

I am trying to find a way to condense this code. I attempted

tableArr[0,1,2].hasClass('userTaken')
but it did not work. Any advice on how to optimize this further?

Answer №1

To achieve this, you can consider utilizing the every method, along with slicing the array. Here's an example of how you can do this:

tableArr.slice(0, 3).every(x => x.hasClass('userTaken'))

In this code snippet, we are taking the first three elements of the array using the slice method, and then checking if the test passes for each element with the every method.

If you are working on a tic-tac-toe game, you may also need to check diagonals, which can be a bit more complex when using .slice. In such cases, you can utilize map as well. Here's how you can do it:

[0,1,2].map(idx => tableArr[idx]).every(x => x.hasClass('userTaken'))

Answer №2

If you want to verify whether an element lacks a specific class, you can use the some method like this:

tableArr.slice(0, 3).some(x => !x.hasClass('userTaken'))

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

Managing arrays that are initialized both inside and outside of functions

Having a function that deals with pointers of pointers, specifically dynamically allocated 2D arrays or matrices through malloc(), I am encountering issues when trying to pass elements between pointers with memory allocated both inside and outside function ...

Guide on retrieving inline style that has been overridden by CSS using JavaScript

<div style="background: url(http://www.example.com/image.jpg) center center/cover;"> This specific background image defined inline is being replaced by a rule in an external stylesheet: div { background-image: none !important; } Here's my q ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Managing various iterations of identical repositories

Currently in the process of constructing a library of unique react components that are being utilized in various downstream applications. To incorporate these components into my downstream applications, I rely on the package.json. Recently, I began ponde ...

VueJS with Vuetify: Issue with draggable cards in a responsive grid

I am currently working on creating a gallery that allows users to rearrange images. To test this functionality, I am using an array of numbers. It is important that the gallery is responsive and displays as a single column on mobile devices. The issue I ...

What is the proper way to connect with the latest Set and Map objects?

Can Angular 1.* ng-repeat function with Set and Map new objects? Is there a roadmap to implement this integration? ...

Tips for creating animated clouds that move across the screen using Flash, jQuery, or JavaScript

Are there methods to create scrolling clouds using tools such as Flash, jQuery or JavaScript? If so, can you provide me with the code required to implement this on my homepage? I have three small cloud images that I would like to animate moving in the bac ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...

How to connect an external module to NuxtJS using Vue.js

Attempting to incorporate a widget/plugin/extension system into my existing web UI built with NuxtJS. Within the pages/view.vue single-file component, I aim to establish the extension system by dynamically loading components indicated through query paramet ...

Node.js application experiencing bug with End of Line (EOL) not displaying correctly

I've encountered an issue with my node.js application that involves writing the following code: word_meaning = 'line 1' + os.EOL +'line 2'; When attempting to render this in an HTML file using the following code: <p> <% ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

Issue with remove functionality in Vue js implementation causing erratic behavior in my script

Within my Vue.js code, I have a functionality that displays categories from an API. When a category is clicked, it is added to the AddCategory array and then posted to the API. I have also implemented a button called RemoveAll which successfully empties th ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

How can we increase the accuracy of numerical values in PHP?

When performing a math operation in JavaScript, the result is: 1913397 / 13.054 = 146575.53240386088 However, when the same operation is performed in PHP, the result is slightly different: 1913397 / 13.054 = 146575.53240386 This discrepancy may be due ...

How to address hover problems in D3.js when dealing with Path elements and updating tooltip information after brushing the focus

Seeking assistance with a Multi Series, Focus + Context D3 chart and hoping to address my main queries all at once. The questions that need resolving are: How can I prevent the tooltips I've generated from being affected by the hair-line (which t ...

What is the best way to execute the angular-phonecat tutorial tests while the server is operating without a graphical user interface?

The angular-phonecat demo assumes that your server has chrome installed and you are running it there. When you run the command npm test, the local chrome browser should launch and continuously run the tests. However, if you are using a headless server li ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Unable to update due to outdated response call causing issues

I am currently in the process of updating outdated response calls and have encountered a peculiar issue where the response is not being properly ended. Typically, I would use : res.send(200, {message: 'Location Updated'}); However, this method ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

Enhance your JQuery skills by implementing variables within the .css() function

Attempting to randomly assign values to an image's left and right properties using JQuery. Here is the code snippet: var sides = ["left", "right"] var currentSide = sides[Math.floor(Math.random() * sides.length)]; $("#"+currentImage).css({currentSide ...