Cannot assign value to property x on y as it is not an object - dealing with Multidimensional Arrays

I'm experimenting with creating a multidimensional array that looks like this:

var minutes = [];
for (let i = 1; i < 10; i++) {
  minutes.push(i);
}
var works = [{
  startTime: 80000,
  endTime: 150000
}, {
  startTime: 200000,
  endTime: 400000
}, {
  startTime: 15000,
  endTime: 80000
}, {
  startTime: 300000,
  endTime: 500000
}];
var sumTime = 0;
var tasksByTime = [];
works.forEach((work, i) => {
  tasksByTime.push(i);
  console.log(tasksByTime);
  var difference = work.endTime - work.startTime;
  minutes.forEach((time, j) => {
    console.log(time * 60 * 1000, difference);
    console.log(i, j);
    if (difference > time * 60 * 1000) {
      tasksByTime[i][j] = (work.id);
    }
  });
  sumTime += difference;
});
console.log(tasksByTime);

My goal is to arrange the objects based on the time difference between startTime and endTime. However, I encounter an issue when attempting to log the result:

TypeError: can't assign to property 0 on 3: not an object

Here's the complete log:

Array [ 0 ]
NumbersPanel.js:35
60000 8498 NumbersPanel.js:40
0 0 NumbersPanel.js:41
120000 8498 NumbersPanel.js:40
0 1 NumbersPanel.js:41
180000 8498 NumbersPanel.js:40
0 2 NumbersPanel.js:41
240000 8498 NumbersPanel.js:40
0 3 NumbersPanel.js:41
300000 8498 NumbersPanel.js:40
0 4 NumbersPanel.js:41
360000 8498 NumbersPanel.js:40
0 5 NumbersPanel.js:41
420000 8498 NumbersPanel.js:40
0 6 NumbersPanel.js:41
480000 8498 NumbersPanel.js:40
0 7 NumbersPanel.js:41
540000 8498 NumbersPanel.js:40
0 8 NumbersPanel.js:41
Array [ [], 1 ]
NumbersPanel.js:35
60000 12580 NumbersPanel.js:40
1 0 NumbersPanel.js:41
120000 12580 NumbersPanel.js:40
1 1 NumbersPanel.js:41
180000 12580 NumbersPanel.js:40
1 2 NumbersPanel.js:41
240000 12580 NumbersPanel.js:40
1 3 NumbersPanel.js:41
300000 12580 NumbersPanel.js:40
1 4 NumbersPanel.js:41
360000 12580 NumbersPanel.js:40
1 5 NumbersPanel.js:41
420000 12580 NumbersPanel.js:40
1 6 NumbersPanel.js:41
480000 12580 NumbersPanel.js:40
1 7 NumbersPanel.js:41
540000 12580 NumbersPanel.js:40
1 8 NumbersPanel.js:41
Array(3) [ [], 1, 2 ]
NumbersPanel.js:35
60000 12366 NumbersPanel.js:40
2 0 NumbersPanel.js:41
120000 12366 NumbersPanel.js

The issue persists until the 4th iteration. Any idea why this happens?

PS. Oddly enough, the code works in the snippet but crashes in the browser.

https://i.sstatic.net/Gvpdo.png

If it's relevant, I'm working with React. If React doesn't fit as a valid tag here, feel free to remove it.

Answer №1

Your outermost forEach function has a bug. You are trying to push the value of 'i' into 'taskByTime', but 'i' is a Number, not an Array.

When you later try to access 'taskByTime[i][j]', you are first retrieving the element at the 'i' position in 'taskByTime', which is a Number, and then treating it as an array - causing it to not work as intended.

To fix this, simply modify your first 'push' statement. You can either add an empty array:

tasksByTime.push([]);

Or add the work instead:

tasksByTime.push(work);

Both options should work logically, but one might be more efficient than the other.

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

Transform the angular code in order to execute innerHTML functions

function campform() { $.ajax({url: "{{ path('campform') }}", success: function(result){ $("#respuesta").html(result); }}); } I am having trouble with the angular code in the result I received. Can anyone provide guidance on how t ...

What is the method for bringing in Mongoose to utilize json.parse()?

I'm really eager to utilize this code for importing a JSON file into JavaScript var treeData; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "test.json", true); oReq.send(); function reqListener(e) { treeData = JSON. ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

The Gulpfile.js encountered an error while trying to load

My Visual Studio task runner is having trouble loading the gulp file. I am currently using VS2017 v15.9.4, but the project was developed some years ago. Failed to run "...\Gulpfile.js"... cmd.exe /c gulp --tasks-simple assert.js:350 throw err; ...

When trying to update a MySQL database, the ampersand is appearing as &amp;amp; instead of the expected &

Currently, I am in the process of creating an administrative section that will allow for easy management of information displayed on the main website. This section will enable users to add, update, and delete content using just one page. Most of my script ...

Revamping MapReduce in MongoDB Version 2.4

After upgrading to MongoDB 2.4, I encountered an issue with a map function that uses db, as mentioned in the release notes. The release notes suggest refactoring, but I am unsure about the best approach to take. The part of the function that is no longer ...

Exploring the integration of PostgreSQL into JavaScript

As a beginner in JavaScript, I am looking to create a web page that can store data in a database. Can anyone provide guidance on what resources or materials I should study to learn more about this process? ...

A dynamic context menu using jQuery within AJAX-loaded content

After spending hours searching for a solution without success, I am turning to this forum for help (I have come across similar questions but none of them have solved my issue). The problem I am facing is with implementing a custom context menu on a page t ...

Interact with a webpage element using Selenium

My goal is to extract information from the following page: I want to interact with each blue stats icon on the page (one for every match of the tournament). Below is the code I am using: from selenium import webdriver from selenium.webdriver.common.by im ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

React Router - Implementing a <Redirect> element rather than a list of child components

Here is the code snippet I am working with: import { Redirect } from 'react-router-dom'; import QPContent from '../QPContent'; class AnswerContainer extends Component { constructor(props) { super(props); this.state = { ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

Guide to integrating google-map-react with Next.js

I can't seem to figure out what's causing the issue. I'm attempting to utilize google-map-react in my Next.js application. I followed the example provided on their npm page almost exactly. Here is the code snippet: import React from "re ...

Strip away all HTML attributes within a string

I am in the process of developing an internal tool that allows a designer to input exported svg code into a text area and have the html code displayed in a syntax highlighter () When they paste their code like this <svg xmlns="http://www.w3.org/20 ...

I discovered that the chips' content was in need of updating once I selected the content from the menu

I want to create a chips feature similar to Google Flights where clicking on the chips opens a menu. Currently, when I click on the chips, the menu opens up and 'Sports' is displayed as a chip. However, I want to update the 'Sports' tex ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

The ReferenceArrayInput request is lacking an api-prefix

I have been attempting to utilize the ReferenceArrayInput component from react-admin in order to modify a OneToMany relationship. Although the options for the multi-select input load correctly, the actual selection does not work as expected. Interesting ...

The odd behavior of how my friends' likes are appearing on Facebook FQL URLs

Hey there! I'm trying to keep track of the number of likes on a specific URL shared by my friends. Here's the code snippet I have: function countURLLikes(url){ FB.api({ access_token:'CAACEdEose0cBABMG67fV8Yn5cHo5fkb ...

What is the significance of curly braces within function parameter declarations in JavaScript?

Recently, I have been exploring a tutorial that delves into setting up React with Redux. While following along, I came across some unfamiliar syntax involving curly braces within function parameter definitions. Can someone explain what purpose these serve? ...