Javascript is unable to access the occupied value. Error: Unable to read property 'weight' of undefined

I encountered a strange issue that I wasn't expecting.

The snippet of code below represents a simple function.

However, the problem arises when I try to access 'truckArray[0].weight' and receive an error stating TypeError: Cannot read property 'weight' of undefined

To confirm that the value is not undefined, I used console.log(truckArray[0]),

function solution(bridge_length, weight, truck_weights) {
    const truckArray = truck_weights.map((v)=>{
        return {
            weight: v,
            movingDistance: 0,
        };
    });   

    const inProcess = [];
    let timeCount = 0;
    let inProcessTotalWeight = 0;

    do {
        timeCount++; 
    
        if ((**truckArray[0].weight** + inProcessTotalWeight) <= weight) {
            inProcess.push(truckArray.shift());
        }
        
        inProcess.forEach((v)=>{
            v.movingDistance += 1;
        })
        
        if (inProcess[0].movingDistance > bridge_length) {
            inProcess.shift();
        }
        
    }while(inProcess.length !== 0 );

    return timeCount;
};

I would appreciate any suggestions or ideas. Thank you!

Answer №1

Can you attempt to access the weight of the first truck using truckArray[0]['weight']

Answer №2

Did you attempt the following:

    if ((parseInt(vehicleArray[0].size) + currentTotalSize) <= size) {

Answer №3

Verify that the truckArray variable contains a collection of actual numbers and is not void of elements.

Answer №4

It seems like your code is functioning properly for the majority of the truck weights array.

However, the issue lies within the loop. With each truckArray.shift(), you are eventually left with an empty array, leading to undefined values when trying to access truckArray[0]. This error occurs when attempting to reference the weight of something that does not exist.

To resolve this issue, make adjustments to your looping mechanism and everything should work smoothly from there :)

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 jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Get the source of a nested iframe inside a parent iframe

On one of my web pages, I have an iFrame that displays the content of another page with its own embedded iFrame. Unfortunately, I do not have control over this external page. I am wondering if there is a way to extract the src attribute of the nested iFram ...

Can't decide between ngOnInit() and ngAfterContentInit()?

As a newcomer to Angular, I sometimes get confused about the ngOnInit() and ngAfterContentInit() lifecycle hooks. According to the official documentation: ngOnInit() : This hook is used to initialize the directive/component after Angular has displayed the ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

custom vertical tab label text not aligning to the right in material-ui with textAlign

I am struggling with customizing the tabs in material-ui to display them vertically. I also want the text labels of these tabs to align to the right for a more cohesive look. Despite trying various styling options, I have not been successful in achieving t ...

How to implement a pop-up dialog box with multiple input boxes using AngularJS?

If you click on the link below: https://material.angularjs.org/latest/demo/dialog You'll notice that the prompt dialog box features only one input field. I'm curious to know if it's possible to customize this using mdDialog to include mult ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Platform Independent Data Storage Solution

Looking to create a Cross-browser compatible Web Application using HTML, JS, and CSS. In need of a robust database storage solution that can be queried on the client side using JS. While Web SQL/SQLite seems like a good option, it lacks support in IE. Does ...

Click on another part of the page to reveal a dropdown menu

I am seeking a way to trigger the opening of this dropdown select not by directly clicking on its position, but rather by clicking on another <span>. Displayed below is the dropdown menu: <div class="styled-select"> <span id="camDurati ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...

Vuejs is throwing an uncaught promise error due to a SyntaxError because it encountered an unexpected "<" token at the beginning of a JSON object

I am currently attempting to generate a treemap visualization utilizing data sourced from a .json file. My approach involves employing d3 and Vue to assist in the implementation process. However, upon attempting to import my data via the d3.json() method ...

Is it possible to scroll down a page using Javascript/jQuery?

Is there a way to implement a "page down" action using Javascript/jQuery that functions correctly even if the user has adjusted their zoom settings? In other words, I need it to scroll exactly as much as it would if the user physically pressed the key for ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...

Exploring the capabilities of qTip2 integrated with jQuery Vector Maps (jqvmap)

Is there a way to disable the default tooltip in jqvmap and replace it with qTip2? Check out this example. Here's the jQuery code: jQuery('#vmap').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffff ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original fo ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

The active tabs or placeholders do not update properly when I click on them

Is there anyone who can help figure out why the tabs are not functioning as expected? The goal is for the tabs to change the input field placeholder and perform a search based on the active tab. If you're able to assist, please review my complete cod ...