Associative TypeScript Arrays

I'm attempting to organize reservations based on business ID in order to achieve a specific end result. Here is the desired output:

[ [businessID1] => [Object1,Object2, Object3], [businessID2] => [Object1,Object2], [businessID3] => [Object1,Object2] ]

Below is the code I am currently using:

let groups = new Array;
this.reservations.map(function (value) {
  groups[value.businessID] = value;
});

However, this approach is not working as expected because it keeps overwriting the array key. As someone new to the TypeScript/JavaScript world, any guidance or suggestions would be greatly appreciated.

Answer №1

In cases where the value is not present, the process involves creating an empty array and then adding the value using the push method:

If the value of groups at businessID is undefined, create an empty array:
if (groups[value.businessID] === undefined) {
  groups[value.businessID] = [];
}
Add the value to the array at businessID:
groups[value.businessID].push(value);

A more concise approach would be:

(groups[value.businessID] = groups[value.businessID] || []).push(value);

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

Guide to smoothly scroll to the top of an element containing collapsible panels using Jquery

I've encountered an issue with a series of divs that are set to toggle the state of a collapsible div upon clicking (similar to an accordion widget). The functionality works as intended, but I'm facing a challenge - I want the page to scroll to t ...

Selenium is throwing an ElementNotInteractableError indicating that the element is not able to be

Today I decided to dive into learning Selenium, but I've hit a roadblock while trying to click on an element that looks like this: <a rel="nofollow" style="" href="javascript:void(0);" time="" itemid="15 ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

Tips on how to ensure that an onClick JS function only runs when radio buttons are selected

I have implemented the formslider library for a form on my website. In the demo, the slide transitions to the next set of questions based on a click event triggered by radio buttons (answers). However, when I attempted to include checkboxes for users to s ...

Incorporate JavaScript strings into HTML dynamically

I am facing some challenges with single quotes while trying to append HTML with a JavaScript string. So far, I have managed to successfully append the element: $("<a class='action-button' id='pl65197buy' value='buy now'&g ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

Specify touch event regions with the ngTouch directive

I recently implemented ngTouch in my AngularJs web app to detect swipe left and right gestures. I am using this feature to open and close a side bar menu. Currently, the swipe events are linked to the entire wrapper like this <div ng-style="body_st ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

Creating a TypeScript mixin with a partial class is a useful technique that allows you to

I am attempting to have class A inherit properties from class B without using the extends keyword. To achieve this, I am utilizing a mixin in the following manner: class A{ someProp: String someMethod(){} } class B implements classA{ someProp: String ...

It appears that using JQuery's .when and .done functions may result in the code executing before the script has finished loading

Since updating the hard-coded <script> with JQuery promises, I have been encountering these errors frequently: https://i.stack.imgur.com/xkWAk.png The issue seems to be inconsistent in replicating. Sometimes, the error occurs while loading the page ...

My objective is to show the div element just once using AngularJS

Here's the scenario I want to show this div just once, not multiple times: //angular js code $scope.arr=["sunday","mpnday","tuesday"]; //html view <ul> <li ng-repeat="x in arr"> <div><p>{{ x }}</p> </div> & ...

Store the results in the database following the execution of a protractor test

I am completely new to angular protractor testing. I have created some test cases using the protractor framework with jasmine runner BDD style. Within a single test class, I have 10 to 12 specs, each with an expectation. Currently, I am running these tests ...

Display scrollable content at the bottom

I am currently working on creating a chat application using JavaScript (AngularJS without jQuery) and I am wondering if it is possible to have a scrollable div load to the bottom automatically. While I am familiar with the scrollTo JS property, I do not f ...

Error message: "Link binding error in knockout collection"

In this example, you'll find my Knockout ViewModel. $(document).ready( function () { var Incident = function (CaseNumber, DateOfIncident, Description) { this.CaseNumber = CaseNumber; this.DateOfIncident = DateOfIn ...

The C# MVC Controller is having difficulty retrieving decimal or double values from an Ajax POST request

Having trouble sending decimal or double values via ajax to my C# MVC Controller. The values always come through as null, even though they work fine when sent as strings or integers. Why is this happening? When checking the client's request, the corre ...

Mismatched URLSearchParam type {property: value} does not match with undefined and Argument Type {property: value} cannot be assigned to {property: value}

Every time I try to run the code below, I encounter this error. The code is supposed to take a refresh token as input and make a POST request using URLSearchParams to a specific URL. However, I keep getting an error related to URLSearchParams. https://i.s ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Setting up pagination in Angular Material can sometimes present challenges

After implementing pagination and following the guidelines provided here. This is my code from the app.component.ts file - import { Component, OnInit, ViewChild } from '@angular/core'; import {MatPaginator} from '@angular/material/paginat ...

Is there a way to modify the edit button to become a save button and include a cancel button?

Is there a way to toggle between an edit button and a save button, along with a cancel option? $('#edit').click(function() { $(this).hide(); $('#save, #cancel').show(); }); $('#cancel').click(function() { $('#ed ...

Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet: app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) { $scope.ite ...