What methods can I use to differentiate between elements in an array?

Apologies if my title isn't clear, I'm struggling to figure out the next steps here.

I've been teaching myself JavaScript.

Right now, I'm working on creating a tic-tac-toe game.

I'm using only vanilla Javascript and lodash for this project.

The board is currently stored as an array and split into 3 rows using lodash.chunk:

For example:

array = [
  [x,x,x],
  [x,o,x],
  [o,o,x],
]

I've managed to determine a winner in the same row, but now I'm stuck on how to check for diagonal or up/down wins.

I just can't seem to visualize what needs to be done next.

If anyone can guide me on how to achieve this using best practices, I would greatly appreciate it.

Thank you!

Answer №1

If you find yourself in a technical interview, be prepared for questions that involve comparing multidimensional arrays. Learn more about multidimensional arrays here

One approach is to iterate through each element in array[0][x] and check if it matches array[1][x]

Answer №2

here is the solution....

let array = [
      ["x","x","x"],
      ["x","o","x"],
      ["o","o","x"],
    ]

    for(let i = 0; array.length > i; i++){
      if(array[i][0].includes("x") && array[i][1].includes("x") && array[i][2].includes("x")) {
          console.log("X wins horizontally")
      }
  
    }


    let array2 = [
      ["x","x","o"],
      ["x","x","o"],
      ["o","o","x"],
    ]


    for(let i = 0; array2.length > i; i++){
      if(array2[i][0].includes("x") && array2[i+1][1].includes("x") && array2[i+2][2].includes("x")) {
          console.log("X wins diagonally")
      }
  
    }

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 reason behind Babel including this redundant line of code in my build?

While utilizing Babel 7 and Gulp 4 in conjunction, I have noticed that the subsequent line of code is repeated five times within my build: function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterato ...

Encountering an error with Angular-NG8001 due to an unknown element. Any suggestions on how

I am encountering an issue with my Angular project. The project structure I am working with can be found here: app structure. Within my app.module.ts file, the code appears as follows: import { NgModule } from '@angular/core'; import { BrowserMod ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

npm encountered a premature closure

I recently purchased and started using a ReactJS template which you can check out here My goal is to install all the dependencies by running npm install in the root directory of the template (React-App) However, I encountered an ERROR message like this: ...

I am looking for a solution to transform JSON data into XML format using node.js

I'm looking to convert JSON data on my node.js server into an RSS feed. Can anyone recommend the most efficient method for accomplishing this task? Additionally, once the conversion is complete, I will need the RSS file to be outputted or overwritten. ...

Uncovering the Solution: Digging into a Nested ng-repeat to Access an Array in AngularJS

I am working with a recursive array in JavaScript: [{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

When working with nested contexts in React, is there a way to avoid causing a rerender of the child context when changes are made to the parent context?

I'm currently utilizing multiple contexts to extract data from different locations within my database. In the code snippet below, the 'path' value that is passed to the provider indicates the specific path within the database. A record in & ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

I'm curious if there is a method to determine the status of a .net required field validator using JavaScript

I am attempting to determine the status of the "required field validators" within an .aspx file. By state, I am referring to whether they are enabled or disabled rather than if their contents are valid or invalid. I am aware that the enabled/disabled sta ...

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

Using the click function is not possible once the append function has been applied

After adding TRIGGER DIV A above $(".DIVB").html(data); from an AJAX Response, I am unable to trigger code using $(".TRIGGER DIV A").click(function(). Can anyone clarify why this is happening and suggest a solution or workaround? ...

Unable to access properties of an unknown item (reading 'remove')

Can you provide guidance on how to remove the top-level parent element of a div? I've been attempting to delete the main parent element of a specific div. element.innerHTML = ` <div class="postIt-item"> <div class="postIt-item-btn ...

Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first fr ...

Delivering static frontend JavaScript file using ExpressJS

Hey there, I'm running into a bit of trouble when trying to load the frontend JS file on my Express server. Here's how my file structure looks: https://i.sstatic.net/EHDSp.png Here's my Server Code - app.set("view engine", " ...