Challenges arise when the value of an element within an entity is 'undefined'

I'm having difficulty sorting and grouping an array of objects. The problem arises when attempting to access the key named 'Driver' as it is returning 'undefined'.

Here is the snippet of code in question:

let driversList = [
    {
        "Driver": "test-000000",
        "Date": "3/15/2020",
        "Status": "Off-Duty",
        "Time": "12:00 AM",
        "": "",
        "__1": "",
        "__2": ""
    },
    {
        "Driver": "test-000000",
        "Date": "3/16/2020",
        "Status": "Off-Duty",
        "Time": "12:00 AM",
        "": "",
        "__1": "",
        "__2": ""
    }
];

let driversByGroup = [];

driversList.forEach((item, index) => {
// Check if the current item.Driver matches the previous or next one, then push it to targeted group in driversByGroup array
    if (item.Driver == driversList[index + 1].Driver || item.Driver == driversList[index - 1].Driver) {
        driversByGroup[item.Driver].push(item);
    } else {
        driversByGroup[item.Driver].push(item);
    }
});

Answer №1

At the start of the first iteration (index equals 0), your code appears as follows

hos.map((item, index) => {
    console.log(index);
    // neither hos[1] nor hos[-1] exist -> undefined
    if (item.Driver == hos[0+1] || item.Driver == hos[0-1].Driver) {
        hosByDriver[item.Driver].push(item);
    } else {
        hosByDriver[item.Driver].push(item);
    }
});

This leads to a crash at the very beginning. The expression hos[0-1].Driver results in undefined.Driver. To avoid this issue, you can use &&.

Note: array[-1] is not invalid syntax

hos[index - 1] && hos[index - 1].Driver

Furthermore, keep in mind that item.Driver is a string. Arrays are usually indexed by numbers, so it seems like you intended to use an Object instead:

let hosByDriver = {};

hos.forEach((item, index) => {
  console.log(index);
  if (hos[index - 1] && (item.Driver === hos[index + 1] ||  item.Driver === hos[index - 1].Driver)) {
    //hosByDriver[item.Driver] = [];
    //hosByDriver[item.Driver].push(item);
  } else {
    hosByDriver[item.Driver] = [];
    hosByDriver[item.Driver].push(item);
  }
});

The change from .map to .forEach was made since you are not generating a new Array to return. If only iterating is needed, forEach is more appropriate.

Based on my assumptions regarding your goal, I have provided a suggested solution. For further clarification, additional details would be beneficial. Check out the codesandbox link for reference:

https://codesandbox.io/s/stackoverflow-3h2n9

It may be helpful to brush up on fundamental JavaScript concepts such as data types and loops. Keep learning! :)

Update: If my understanding is correct, you aim to group Drivers in hosByDriver based on matching names stored in hos. This grouping allows easy access to all items of a driver like hosByDriver['test-000000'] without repetitive array iterations.

You can accomplish this efficiently as follows

let hosByDriver = {};

hos.forEach(item => {

  // Check if item or item.Driver may deviate from expectations 
  // with conditional statement:
  // item && item.Driver && typeof item.Driver === "string"
  if(!hosByDriver[item.Driver]){ 
    hosByDriver[item.Driver] = [];
  }
  hosByDriver[item.Driver].push(item);
});

Additional Information:

In JavaScript, Arrays are essentially Objects with key/value pairs. For more insight, consider watching JavaScript: Understanding the Weird Parts. While arrays allow indexing with numbers starting from zero, using strings in place should be avoided for clarity and easier debugging.

It is advised to refrain from using == and opt for === to prevent unintended type conversions. For instance, 0 == "" evaluates to true, leading to potential complications and errors.

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

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

Store Form Input as JSON Data File

Seeking advice on the optimal method to save submitted form data to a separate file called data.json, for future reference. The form layout is quite basic: <form> <fieldset> <label for="name">Name:</label> &l ...

Issue with GLTF Loader Trial: Encountering TypeError when trying to resolve module specifier "three". Invalid references detected; relative references must begin with either "/", "./", or "../"

I'm relatively new to working with three.js and I am currently attempting to load a model into my canvas. However, when I import the GLTFLoader, I encounter the error message mentioned in the console above. Despite checking the syntax and relative pat ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

Converting a class to a JSON object with ArraySegment

I am currently grappling with a particular issue, I am aiming to transfer a Json object using ArraySegment my JSON Data conforms to this structure {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, ...

Jquery selector failing to target correct <form> element within Shopify theme

I'm feeling a bit lost here! Trying to zero in on a form within my page and utilize jQuery's serializeArray() function to extract all the values from said form. <div class="page-width"> <header class="section-header ...

Iterating through a 2D array using KnockoutJS foreach loop

I am working on binding a JSON string returned from the server to a foreach loop using KnockoutJS. The JSON structure is as follows: [{"FileID":19, "ParentID":6, "SubType":"Page", "FileName":"nav_secondary_bg.png", "FileExtension":null,"Filetype":"20 ...

Navigating the json return values within an angular.js action success callback can be achieved through the following

Attempting to perform a POST request with angular.js resources and implementing success and error callbacks. wbsModule.factory('gridData', function($resource) { //define resource class var root = {{ root.pk }}; var csrf = '{{ cs ...

Error encountered: Attempting to wrap MuiThemeProvider in App resulted in an invalid hook call

Whenever I include MuiThemeProvider in App.js, I encounter an error that prevents the page from loading. This issue is puzzling to me since I have utilized it successfully in other projects. react.development.js:1476 Uncaught Error: Invalid hook call. Ho ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

Is there a way to repurpose a JavaScript object that gets sent back to the client upon page loading?

Upon initial page load, an AJAX request fetches a list of JavaScript objects which display only one value each. The page includes buttons to expand each item and reveal the remaining values. Originally, I used another AJAX call to retrieve individual objec ...

How do I display form results in JSON format after submission in Laravel?

Is there a way in Laravel to display form results in JSON format without needing to save them to the database first? The purpose is to verify and validate the data entered in the form. ...

Managing multiple element click events through bubbling

I have a collection of controls contained within a main div called overlay-controls. Each control has its own set of overlay-controls. To handle deletion, I am using a for loop to attach an event listener to each button with the class delete. Prior to a ...

When it comes to adjusting the height of an element, there are two ways to go about it: using $(element).height

function adjustHeight(){ var headerHeight=$(element).find('.header').outerHeight(); console.log(headerHeight); var temp=$(window).height()-headerHeight; console.log(temp); $('.users ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

How can we use JavaScript to create visual representations of data pulled from a JSON file?

I am interested in utilizing a library similar to the Google Visualization API for creating charts, but with the ability to retrieve data as JSON from an external source. Specifically, I intend to use an SPARQL service to extract information from an XHTML+ ...

Why isn't my React image updating its source right away? What are some solutions to this issue?

I currently have a basic <img> tag with a specified src attribute. <img src={src} /> When I update the src attribute from, let's say /1.jpg to /2.jpg, there is a delay in loading the new image. React still displays the old image (/1.jpg) ...

Guide to adding a Scrollable Navbar

Is the term "scroll bar" really accurate? I want to create a scrollable feature where users can easily select a city using their mouse wheel (or swipe on a smartphone) and then choose from possible cities within that country in a second window. Something s ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...