How can I populate an array using values from a different array in Angular?

I am facing an issue with populating three other arrays based on the property 'game type' from my array called 'my games'. Here is an example of the structure of the 'my games' array:

hideScore: true, started: true, startedAt: "Fri, 02 Jul 2021 09:04:25 GMT", finished: true, finishedAt: "Fri, 20 Aug 2021 15:35:37 GMT", …}
archived: false
bgGame: "#1a1f29"
 client: "client test"
 company: "tunisia"
 country: "Tunisia"
 createdAt: "2021-07-02T09:03:34.015Z"
 finished: true
 finishedAt: "Fri, 20 Aug 2021 15:35:37 GMT"
 gameType: "test"
 hideScore: true
 id: "60ded6668734e65c51f50996"
 language: "English"
 maxLevel1: 10.47195
 maxLevel2: 2.065616666666668
 maxScore: 23400
 name: "game test"
 nbrDoors: 8
 nbrPlayersPerTeam: 8
 partner: "khouloud ben khssib"
 playtime: 30
 started: true
 startedAt: "Fri, 02 Jul 2021 09:04:25 GMT"
 startsAt: "Fri, 02 Jul 2021 09:03:00 GMT"
 teams: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
 teamsCount: 20
 textColor: "#ffffff"
 updatedAt: "2021-08-20T15:35:37.348Z"
 user: "609321b935e3f04d04d44337"
 __v: 0
 _id: "60ded6668734e65c51f50996"
 

I have three arrays named 'NumberofLive', 'NumberofTest', and 'NumberofDemo'.

NumberofLive: any[] =[];
 NumberofTest: any[] =[];
 NumberofDemo: any[] =[];
 

Every time I want to populate a table, I try something like this:

for(let i=0;i<this.MyGames.length; i++){
      
      switch(this.MyGames[i].gameType) { 
        case 'test': { 
        
          this.NumberofTest=this.NumberofTest+this.MyGames[i];           
           break; 
        } 
        case 'live': {                  

                          this.NumberofLive=this.NumberofLive+this.MyGames[i];           

           console.log('salzem');     
           console.log(this.NumberofLive[1].gameType);
           
           break; 
        } 
        default: {              

          this.NumberofDemo=this.NumberofDemo+this.MyGames[i];           
           break; 
        } 
     } 

    }
 

However, when I log my table, I find that it returns 'undefined'.

Answer №1

It's important to remember that when working with arrays, you can't simply add them together with the "+" sign; new objects need to be pushed into the array instead.

this.NumberofTest.push(this.MyGames[i])

For a more streamlined solution, consider using the array.filter method rather than a traditional for loop:

this.NumberofTest = this.MyGames.filter((item) => item.gameType==='test')

Answer №2

After some adjustments to your code, please find the updated version below

for(let i=0;i<this.MyGames.length; i++){   
  switch(this.MyGames[i].gameType) { 

    case 'test':  
         this.NumberofTest.push(this.MyGames[i]);           
         break; 
         
    case 'live':                
         this.NumberofLive.push(this.MyGames[i]);   
         break; 
         
    default:             
         this.NumberofDemo.push(this.MyGames[i]);
  }  
}

Here's an alternate approach:

this.NumberofTest = this.MyGames.filter((item) => item.gameType === 'test');
this.NumberofLive = this.MyGames.filter((item) => item.gameType === 'live');
this.NumberofDemo = this.MyGames.filter((item) => item.gameType !== 'test' && item.gameType !== 'live');

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

The visual representation remains unchanged even after updating the model

I'm currently tackling an issue with my football project, specifically when updating a service model. The project involves two key components - AvailablePlayers and SelectedPlayers, as well as two corresponding services - AvailablePlayersService and S ...

The value I'm receiving for my list of objects is not accurate

Currently, I'm experimenting with implementing TYPEHEAD for user input using the ng-bootstrap library. The goal is to display a list of objects (similar to a select option without a dropdown box): HTML <input type="search" #instance="ngbTy ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

Steps for integrating custom slot properties in MUI data grids

Custom pagination has been successfully implemented using the mui datagrid component. However, when attempting to pass props for pagination using datagrid's slotProps, an issue arises stating that the type of onChange does not match. How can this be c ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this ...

Sharing code between Angular 8 and NodeJS 12: Best practices

Can code be shared between Angular 8 (TypeScript) and NodeJS 12? All the code is located on the same server but in separate directories /client and /server. A major issue we are facing is the duplication of regular expressions and constants across both A ...

Tips for obtaining results from a File Reader

I am currently facing an issue with an onchange event in my HTML. The event is intended to retrieve an image from the user, convert it to a data URL, and then send it over socket.io to store in the database. However, I am struggling to figure out how to ac ...

Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application. My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once t ...

Unlock the canGoBack feature in your Ionic 5 app with these simple steps!

I'm currently working on implementing a back button in my Ionic app, but I am running into an issue. I need to hide the back button when it's at the root level, which is dynamic and can change based on the flow of the app. I came across some code ...

Utilizing the onBlur event to control focus within a React element

In the React component I'm working on, I have implemented an onBlur event handler. The logic inside this handler is supposed to return focus back to the target element. This code is written in TypeScript. emailBlur(e: React.FocusEvent<HTMLInputEle ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

Incorporating interactive elements within an NgFor loop

My goal is to develop a component that takes another component as a parameter and generates a collection of instances of this component, with the ultimate objective being the creation of a versatile backoffice. Here's an example of how it could look: ...

Retrieve the attribute of a JSON data structure

I'm encountering an issue while trying to access the property of a JSON object named date in my Angular 6 project. Even though I assigned a variable to it, it keeps showing up as undefined. This is the snippet of code causing trouble: getHistorial(d ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Tips for correctly implementing an authorize function in TypeScript with NextAuth.js

Trying to implement the Credentials Provider in NextJs ("next": "^12.0.7") and NextAuth ("next-auth": "^4.1.2") using TypeScript has been a challenge. I am encountering difficulties in getting the function to work co ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Is Angular's forkJoin being phased out?

Upon opening my Angular project today, I came across a warning message that said: The utilization of forkJoin is marked as deprecated: resultSelector is deprecated, it is recommended to use pipe to map instead (deprecation) https://i.sstatic.net/vFpeu.pn ...

Tips for optimizing the performance of an Angular 2 website

I am currently developing a website in Angular 2 and have successfully completed one module which I uploaded to the demo path. However, when I tested it using Google Speed Test, it only received a speed score of 37 on desktop and 32 on mobile. Can anyone ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...