Storing Information in a Two-Dimensional Array using JavaScript

Looking to loop through the Data array and indicate with an "O" if it contains the specified Month and Number. For example, for "Jan-1", Array1[0][0] should be set to "O". However, the code provided below is not working as expected. Any assistance would be appreciated.

var Data = ["Jan-1", "Feb-4", "Apr-5"];
var Month= ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];
var Array1 = [[]];

for (var k = 0; k < Data.length; k++) {
    var split = Data[k].split("-");
    for (var z = 0; z < Month.length; z++) {
        for (var s = 0; s < Number.length; s++) {
            if (Month[z] == split[0] && Number[s] == split[1]) {
                Array1[z][s] = "O";
            } else {
                Array1[z][s] = "X";
            }             
        }
    }
}
number/month |  Jan  |  Feb  |  Mar  |  Apr  | May
------------------------------------------------------
     1       |   O   |   X   |   X   |   X   |   X  
     2       |   X   |   X   |   X   |   X   |   X  
     3       |   X   |   X   |   X   |   X   |   X  
     4       |   X   |   O   |   X   |   X   |   X  
     5       |   X   |   X   |   X   |   O   |   X  

Answer №1

To efficiently compare the elements in the Number and Month arrays, create a loop that checks for the presence of the combination Month[j] + "-" + Number[i] in the Data array:

var Data = ["Jan-1", "Feb-4", "Apr-5"];

var Month = ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];

var result = [];


for (var i = 0; i < Number.length; i++) {                   // loop through each number
  result[i] = [];                                           // create a row for the current number
  for (var j = 0; j <Month.length; j++) {                   // iterate over each month
    if (Data.indexOf(Month[j] + "-" + Number[i]) !== -1) {  // check if the current combination is present in the Data array
      result[i][j] = "O";
    } else {
      result[i][j] = "X";
    }
  }
}

result.forEach(function(row) {
  console.log(row.join(" | "));
});

Answer №2

Reviewing the provided code:

var Data = ["Jan-1", "Feb-4", "Apr-5"];
var Month= ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];
var Array1 = [  ["X","X","X","X","X"],  ["X","X","X","X","X"],  "X","X","X","X","X"],  ["X","X","X","X","X"],  ["X","X","X","X","X"]]; //Setting all elements to "X" initially. Only changing specific indexes.

for (var k = 0; k < Data.length; k++) {
    var split = Data[k].split("-");
    for (var z = 0; z < Month.length; z++) {
        for (var s = 0; s < Number.length; s++) {
            if (Month[z] == split[0] && Number[s] == split[1]) {
                Array1[z][s] = "O";
            } else {
                //Array1[z][s] = "X"; Avoid changing here as the loop iterates over the entire array multiple times. This could overwrite previous changes.
            }             
        }
    }
}

Lastly, execute console.table(Array1); to display values.

Insight: The rows are assigned as months and columns as days during initialization, yet the desired output expects the opposite. To achieve the desired result, either print in transposed form or adjust the values during definition:

if (Month[z] == split[0] && Number[s] == split[1]) {
            Array1[s][z] = "O";
        }

Answer №3

To create a new array containing data represented by 'O' or 'X' based on the given data set, you can iterate through the month and number arrays.

var data = ["Jan-1", "Feb-4", "Apr-5"],
    month = ["Jan", "Feb", "Mar", "Apr", "May"],
    number = ["1", "2", "3", "4", "5"],
    result = [],
    hash = Object.create(null);

data.forEach(function(s) {
    var [m, d] = s.split('-');
    hash[m] = hash[m] || {};
    hash[m][d] = true;
});

result = month.map(function (m, z) {
    return number.map(function (s) {
        return (hash[m] || {})[s] ? 'O' : 'X';
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Angular Satellizer causing issues with Facebook login on mobile devices

Issue Currently, I'm developing an application using Angular and have successfully integrated Facebook login through Satellizer. The functionality works flawlessly on desktop browsers; however, when accessed from mobile devices, it tends to be unreli ...

Utilize Vue.js to sort by price bracket and category

Hello, I am currently new to working with Vue.js and I am attempting to create two filters - one for price range and the other for genre. Any guidance or assistance would be greatly appreciated. Below is a snippet of my code: ul class="filter-wrapper"&g ...

How can I ensure that the images span the entire width of the page in ResponsiveSlides?

I am trying to make my images occupy the entire width of the page just like in this example: However, I have not been able to find a property for this. I'm new to using Jquery but I have a good understanding of Javascript Can someone please help me ...

What causes the v-for in a template to only update when the input text changes?

I'm currently working on a Vue.js code, but I'm facing an issue where the template isn't updating when new data is added to the input text. My goal is for the list to update when the @click event occurs. Visit this link for reference metho ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

Tips for integrating both client-side and server-side validation techniques in your web application

After conducting some research, I have come across information indicating that it is feasible to implement both client-side and server-side validation simultaneously. However, my focus is not solely on learning JavaScript; I am also interested in utilizi ...

Every time I use my NodeJS MySQL Query function, the results I get are never

Working on a new gaming project involving MySQL for multiplayer functionality. Issue arises when requesting specific queries, where the system retrieves incorrect data or results from previous queries. dat("SELECT * FROM server1;"); Misdirected queries r ...

Generate a unique splatter design using Cascading Style Sheets

Imagine a circle link that transforms into a playful animation with a pink shape when you move your mouse over it: I'm torn between different ideas on how to achieve this effect. One approach could be to use individual elements for each drop, utilizi ...

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

implementing geolocation using jquery and javascript

I am currently learning JavaScript and experimenting with the geolocation function in my HTML and PHP code, following a tutorial like this one. Here is the code snippet I added to my custom.js file: $(document).ready(function() { 'use strict&apos ...

Having trouble implementing the FCKeditor in a Zend form

I am trying to integrate FCKeditor with my form by downloading the CKeditor library from Although everything seems to be working fine, I keep encountering the following error: ReferenceError: ReferenceError: CKeditor is not defined Here is the JavaScri ...

Vue.js behaving abnormally due to certain circumstances

Currently, I am working on a vue application where I encountered some errors related to script execution on certain websites. By implementing the following code snippet, the issue is resolved: if ( window.location.href === 'chrome-extension:// ...

What steps can I take to ensure that WebStorm properly recognizes a package's functions?

No matter what I do, WebStorm refuses to stop throwing inspection warnings when I try to use the JOI package in my node.js project. The code runs fine and there are no runtime errors, but the warning persists. I have updated the package, explicitly install ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...