How to utilize the includes() method in JavaScript to compare arrays within a 2D object

Attempting to match the user input arrays (this.scoreO or this scoreX) with the this.winningBoard array, but not requiring exact values. The order of values may be different and I want to identify a match even if there are additional values in the "score" array.

For instance, consider:

this.scoreO = [9,5,2,1]

I want it to trigger a match with [1,5,9] as shown below:

this.winningBoard = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[3,5,7],**[1,5,9]**]

Below is the code snippet:

function Game (player) {

this.winningBoard = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [1,4,7],
    [2,5,8],
    [3,6,9],
    [3,5,7],
    [1,5,9]
]   
this.scoreO = [];
this.scoreX = [];

}

Game.prototype.findWinner2 = function() {

for(i = 0; i < this.winningBoard.length; i++) {

    if (this.winningBoard[i].includes(this.scoreO) === true) {

        //display player 1 "O" is the winner


    } else if (this.winningBoard[i].includes(this.scoreX) === true) {

        //display player 2 "X" is the winner


    } 
}
}

Encountering unexpected outcomes.

Answer №1

To achieve this task, you can utilize a combination of some, every, and includes (if you have access to es6 syntax):

var winningBoard = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [1,4,7],
  [2,5,8],
  [3,6,9],
  [3,5,7],
  [1,5,9],
];

var score0 = [9,5,2,1];

console.log(winningBoard.some(board => board.every(x => score0.includes(x)))

The logic behind this is checking if there exists at least one element in the winningBoard where every item in that element is also present in score0.

ADDENDUM: Here's an extra breakdown:

x => score0.includes(x)

This function evaluates as true if the array score0 contains x as an element. It functions directly on numerical values in this context.

board => board.every(x => score0.includes(x))

The every method returns true only when its callback holds true for each element within the array. Therefore, with board representing a winning number sequence (such as [1,5,9]), this condition will be met if all numbers in that sequence are members of score0.

Ultimately:

winningBoard.some(board => board.every(x => score0.includes(x)))

Unlike every, some verifies whether the callback function is true for any of the array elements. So, this statement becomes true if any of the sequences entirely coincide with score0, which aligns precisely with the desired criteria being evaluated.

Lastly: the syntax x => x*2 serves as shorthand for function(x) { return x*2 } (albeit with some scope distinctions not pertinent here). More details regarding arrow functions can be found here.

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

Implementing the async/await pattern within Vue.js

Implementing the async/await pattern in my new Vue.js project has been a challenge. During my initial attempt, an error was thrown: <template> <div> <table> <tr> <th>Test</th> ...

Enhancing a Class using Jquery

It might sound strange, but I have a full URL as a class for some of my HTML elements. Obviously, this doesn't work for CSS purposes. What I want to achieve is to remove everything except the page slug. Here's an example of what I currently have: ...

Ember.js: Storing function prototypes as objects

My interface consists of four vertical panels: The first panel displays the menu for selecting data The second panel allows you to choose a filter from a list The third panel shows the results based on the selected filter The fourth panel displays detail ...

Using CSS or Javascript, you can eliminate the (textnode) from Github Gist lists

My goal is to extract the username and / values from a series of gists on Github Gists. The challenge lies in the fact that there are no identifiable classes or IDs for the / value. https://i.stack.imgur.com/9d0kl.png Below is the HTML snippet with a lin ...

Use JavaScript to close a modal by simulating the pressing of the "esc" key within the

Is there a way to programmatically close all modals in Javascript without having to press the escape key manually? I tried running the following code in the browser console, but it didn't work at all. Can anyone help me resolve this issue? document.di ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

What could be the reason why my POST endpoint isn't able to receive this AJAX request?

I am currently working on a JavaScript function that is supposed to send JSON data to my escreve POST REST method. $(document).ready(function() { $("#idform").on('submit', function(e) { e.preventDefault(); alert($("#idform"). ...

Using the jQuery.grep() method to sort through data

I have been attempting to filter data that is stored in a .js file using the jQuery.grep() method, but unfortunately, the data is not loading as expected. Data var myData = { "type": "FeatureCollection", "crs": { "type": "name", "properties": {"name": ur ...

Modify a field in every document and nested document by using a specific query in MongoDB with NodeJS

I am struggling with a complex query that involves searching for and updating a dynamic field in multiple embedded documents within a parent document. The challenge is to avoid manual iteration through each document and ensure that the field is updated at ...

Preventing navigation to other tabs in Bootstrap tabs during validation

I am running validation on tab one input fields when the second tab is clicked. Please take a look at my HTML code: <ul class="nav nav-tabs makeblock" role="tablist"> ...

Having trouble retrieving array information in Javascript

I've recently started learning programming and JavaScript, but I'm struggling to access data within an array. Below is a snippet of my code: global.arr = []; var id = 12; for (var i=0; i<5; i++) { arr.push(id); id++; } console.log(arr) ...

Generating dynamic rowspan values for nested levels within a multi-level table using JavaScript and a JSON array

Trying to dynamically calculate the rowspan for each cell in a nested JSON array, which represents a multi-level table structure. Example of input data: [ { "name": "goal1", "children": [ { ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...

Are you sure all of your statements have been successful? This is the problem

Implement a selection sort algorithm that swaps values at a given position with the minimum value index. Use the swap and indexOfMinimum functions provided below. Despite following the logic, there seems to be an issue preventing the code from successful ...

Transmit the Selected Options from the Checkbox Categories

Here's an intriguing situation for you. I've got a webpage that dynamically generates groups of checkboxes, and their names are unknown until they're created. These groups could be named anything from "type" to "profile", and there's a ...

Checking the current password using AngularJS and Laravel for custom validation techniques

I initiated an angular + laravel project yesterday, but I encountered an error in angular which has halted my progress. Below is the code snippet: <div class="form-group" ng-controller="CheckPawd"> <label>Current Password</label> &l ...

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Tips for eliminating any hidden image whitespace in a category filtering system

I recently implemented a category filter feature that hides images I don't need. When I click on the car logo at the top, I want to hide every element that doesn't have the "car" id. However, I'm facing an issue where hidden images still ret ...

Enhance the state by incorporating a key string in the setState function

Need help with my react component that has input boxes. I want to ensure they are not empty. Upon componentDidMount, I call the function: this.validateInputLength(this.state.first_name, 'firstNameValid'); Here, I am passing in the value of thi ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...