Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting elements in a specified order.

let winArray = [playerSymbol, playerSymbol, playerSymbol]
if (playingFielddArray.slice(0, 3).every(v => winArray.includes(v))) {
    // Do something }

While this method works well, it only applies to ordered elements. For non-sequential elements, my approach involves creating multiple arrays for comparison.

let newArray = [playingFielddArray[0], playingFielddArray[4], playingFielddArray[8]]
if(newArray.every(v => winArray.includes(v))){ // Do something }

However, I find this solution cumbersome as it requires creating numerous arrays for comparison purposes. Is there a more efficient function or method that I can utilize for this task?

Answer №1

In a game of tic-tac-toe, to determine if there is a winner, you can create a function that loops three times and checks certain positions:

[i*3, i*3+1, i*3+2] // for checking horizontal rows
[i, i+3, i+6] // for checking vertical columns
[i,i+4,i+8] // for diagonal check when i=0
[i, i+2, i+4] // for diagonal check when i=2

If these positions contain the same icons, names, or ids, then there is a match.

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

Prevent the onClick event in the parent container div from triggering when clicking on a child element

Having trouble with event bubbling and onClick functions within a card element. The card has a heart icon that triggers an onClick function to unlike the card, but it also triggers the onClick function for the entire card which leads to a different page wi ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

Obtain data from a struct within a Swift file

Recently, I created a UserAccount class in my Swift file with various properties like userName, email, instaGram, and more. Here's a snippet of how the class looks: class UserAccount { var userName: String! var email: String! var instaGram: Strin ...

Rotation to a point in a circle using three.js

Currently, I am in possession of 2 instances of THREE.Vector3(). My task at hand is to create a circular shape around one vector with the second vector serving as a tangent. I have determined the radius of the circle geometry based on the distance betwee ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

Nonspecific _POST parameter error encountered while utilizing XMLHttpRequest()

I am currently experimenting with Ajax to add data into a database using the POST method. However, I am facing an issue where PHP is unable to recognize the post variables being sent. ajax: function createUser() { var _id=document.getElementById('ne ...

What methods can a Java application use to distinguish one browser from another?

Is there a way to determine if the browser being used is Firefox or Chrome? I am looking to create an application that will only run on a specific browser registered by a user. To achieve this, my application needs to be able to identify which browser the ...

Identifying the JS Tree nodes that have been repositioned via drag-and-drop

I'm working with a JS Tree structure that includes drag and drop functionality. Here's the basic code I have so far: $('#using_html_1').jstree({ "core": { "check_callback":true }, "plugins" : ["dn ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

What is the best way to utilize a promise for a singular variable?

In my code, I have a requirement where I need to make two HTTP requests. The second request is dependent on information retrieved from the first request. Initially, the first request sets the variable 'amount' which is later used in the second re ...

Can these two arrays be merged together in JavaScript?

Here is the structure of the first array: [ 0:{program: id_1}, 1: {program: id_2} ] Now, let's take a look at the second array: [ 0: [ 0: {lesson: name_1}, 1: {lesson: name_2} ], 1: [ 0: {lesson: name_3} ] ] I am attempti ...

Implementing class attributes in VueJS functional components

Creating a VueJS functional component to emulate div behavior involves setting its class based on the props it receives. For example: <MyDiv textAlign="left">Div with left aligned text</MyDiv> Transforms into: <div class="text-left">Di ...

How can I easily activate a C# class from an asp.net webpage?

I have three labels in my asp.net page: One with a default name for filtering Another filled with a list of names to click on for new filter A third one with a list of items to be filtered The content of the second and third labels is loaded by C# code ...

Error: The expression `xmlDoc.load` returns a value of undefined, which is not an object

My current challenge involves loading an XML file using Javascript in IE, Firefox, and Safari. I have yet to find a function that works well across all three browsers. The load function I am currently using is similar to the one found in w3schools tutorial ...

Use the regex tag in a React component to find a specific tag by name within two different possible

Looking for a regex that can identify <Field ...name="document"> or <FieldArray ...name="document"> within a multiline text string so they can be replaced with an empty string. The text string is not formatted as HTML or XHTML, it simply conta ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...

React Native: The function `useContext.getItemsCount()` is returning a value of undefined, which is not an object

As a newcomer to React Native, I encountered an error when calling getItemsCount. *To view images, please click on the following links: https://i.sstatic.net/wbwjZ.png This snippet shows the code for CartIcon.js: import React, {useContext} from 'r ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...

retrieve a subdocument from an array in MongoDB

In my MongoDB database, I have the following data structure: {doc: { array_doc:[....//many documents]} } Currently, I am working with Mongoskin in MongoDB 2.2 with Node.js 0.8. var code_doc='HSKD41814541211'; var db = mongo.db(perm+"@127.0 ...