Manipulating values within a multidimensional array using JavaScript

I am attempting to populate a multidimensional array with data from a JSON file.

The issue I am facing is that I am unable to update the content in the array:

if(j>i && hoursYy == hoursY && secondsX == secondsXx){
  wocheArray[i].count = wocheArray[i].count + 1;
}

My intention was for the "count" to increment every time a duplicate is found in my JSON file. So far, I have been unable to find a solution online.

Just in case, here is the full code:

var myweek;
var x;
var y;
var id;
var count;
var wocheArray = [];

function preload(){
myweek = loadJSON("data/data.json");
}

function setup(){
createCanvas(windowWidth, windowHeight);
background(0);

//SAVE IN WOCHEARRAY
for (var i = 0; i < myweek.woche.length; i++) {

hoursY = myweek.woche[i].stunden;
secondsX = myweek.woche[i].sekunden;

for (var j=0; j< myweek.woche.length; j++){
 hoursYy = myweek.woche[j].stunden;
 secondsXx = myweek.woche[j].sekunden;

if(j>i && hoursYy == hoursY && secondsX == secondsXx){
  wocheArray[i].count = wocheArray[i].count + 1;
}

else {
  x = myweek.woche[i].stunden;
  y = myweek.woche[i].sekunden;
  id = myweek.woche[i].person;
  count = 0;
  }
wocheArray[i] = {x, y, count, id};
}
}
console.log(wocheArray);
}

Answer №1

The issue lies here:

wocheArray[i] = {x, y, count, id};

If you review your code, you will notice that this section is causing an overwrite.

Consider the scenario where a duplicate is identified.

What will happen within your for loop:

1.) Initialize var count = 0;

2.) [Skipping to If condition where the check occurs]

//IF match found (at j = 2 location, and i = 1)
//then the following takes place : 

if(2 > 1 && hoursYy == hoursY && secondsX == secondsXx){
   wocheArray[1].count = wocheArray[1].count + 1;
// at this point, the count of wocheArray[1] would increase by 1, let's say it becomes 1.
}

3) Inside the else block, count = 0; is set once again.

4) On attempting to set values of

wocheArray[1] = {x, y, count, id};
again, with count reset to 0.

This shows that there is constant updating or overwriting of values leading to unexpected outcomes.

The appropriate approach is to not call this outside

wocheArray[i] = {x, y, count, id};

You should include it within the else block for correct functionality.

else{
x = ....
....
....
count = 0;
wocheArray[i] = {x, y, count, id};
}

It is worth questioning the use of count = 0; inside the else block as it serves no purpose in this context and var count = 0; within the for block which simply re-initializes the count variable, potentially leading to wastage of memory or being considered a poor practice based on the provided code snippet.

Answer №2

By improving the structure of your code, it becomes apparent that

wocheArray[i] = {x, y, count, id};

lies beyond your if else condition. Consequently, wocheArray[i] gets overwritten at the conclusion of each loop.

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

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

How can I use JavaScript api calls to retrieve an image url and insert it into an image tag in an

I have a JSON object that I need to use to retrieve images from a remote URL and display them in the img tag using API calls. The API link can be found at <div class="emoji"> <ul id="emojiz"></ul> <span style= ...

Guide on Crafting an Interactive Breadcrumbs Component

How can I implement product category breadcrumbs on the product page? These breadcrumbs will represent the parent category of the product. I am utilizing Next.js and Strapi for this project. For example, here is a screenshot showing how it should look: ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Expanding the content of a single page by clicking on a separate tab

I have a link on Page A. Page B has two tabs, with the content of tabs 1 and tab 2 currently set to "display:none". I want clicking the hyperlink on page A to automatically open or activate the second tab on page B. I am seeking a solution using JavaScri ...

Encountering a 403 error while using the YouTube API

I have a setup where I display the latest uploaded YouTube videos on my channel. Everything seems to be working fine, but occasionally I encounter this error that causes my entire site to break! [phpBB Debug] PHP Warning: in file /my_youtube/functions.php ...

Error retrieving JSON information

My server's JSON data is currently empty. public class Main2Activity extends Activity { final Context context = this; } @Override protected void onCreate(Bundle savedInstanceState) { } } I am able to re ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

Utilizing JavaScript in AJAX Responses

Can I include JavaScript in an AJAX response and run it, or should I only use JSON or plain HTML for a more elegant solution? I'm trying to figure out the best way to handle AJAX requests that involve inserting HTML or running JavaScript based on user ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

Restricting Entry to a NodeJS Express Route

Currently, I am in the process of developing an express project where I have set up routes to supply data to frontend controllers via ajax calls, specifically those that start with /get_data. One issue I am facing is how to secure these routes from unauth ...

Leverage NodeJS data within Angular framework

I am working with the following route: Server app.get('/claim/:id', compact.js(['global']), indexController.claim); module.exports.claim=function(req,res){ res.render('claim-note', { title: 'claim', noteId:req. ...

New and personalized bindings in knockout.js for dynamically updating a dropdown menu based on the selection in another dropdown menu

I have been using knockout for a few months now and have been getting along just fine. However, I recently encountered an issue where I cannot update the options within a SELECT tag because the ajax methods that retrieve data from the server are inside a ...

Determine which points fall within a specified radius by utilizing solely an array

I'm developing an application that utilizes Leaflet to store GPS coordinates of specific locations in a table format [lat,lng]. This functionality is only accessible from the back end. On the front end, I need to retrieve the current position and gen ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

What's the best way to update keys and values using regex pattern matching?

Need some assistance with jq: Is there a way to find "name" fields in JSON starting with an underscore (ex: _RDS_PASSWORD) and remove the underscore, resulting in RDS_PASSWORD? How can I utilize jq to locate "name" fields beginning with an underscor ...

How can I invoke object functions stored in an array using Javascript?

I'm currently attempting to iterate through an array of game objects and invoke their update methods. The challenge is that game objects may have different update implementations - for example, the update function for an enemy is different from that o ...

The function you are trying to call in Javascript is currently unavailable

I encountered an issue with a JavaScript script. I have an object that contains some functions and variables. Within one of these functions, I make an Ajax request. However, in the error handler, when trying to call a function defined within the same objec ...

Error message: R plumber is having trouble interpreting JSON arguments

As mentioned in the Plumber documentation, it is possible to pass function arguments in JSON format. Consider the following server setup: #* Calculate the sum of two numbers #* @param a The first number #* @param b The second number #* @post /sum function( ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...