Explore an array to find out the frequency of each object's usage

Within our system, we have two arrays: AnswersList[], which contains all potential answers for questions. We then further divided AnswersList[] into six separate arrays: gender, age, disability, ethnic origin, religion, and sexual orientation. For this specific issue, let's focus on genderList[].

The primary array is EqualityAnswers[], which is of type IApplicantAnswers.

import {IAnswers} from "../Enum/answer.model";
export interface IApplicantAnswers {
    ApplicantAnswersKey: number;
    CompetitionKey: number;
    Gender: IAnswers;
    Age: IAnswers;
    SexualOrientation: IAnswers;
    Religion: IAnswers;
    EthnicOrigin: IAnswers;
    Disability:IAnswers;
}

Our goal is to examine genderList[], also of type IAnswer.

export interface IAnswers {
    AnswerKey: number;
    QuestionKey: number;
    Name: string;
    Description: string;
}

We aim to analyze each genderList[i].AnswerKey to determine how many individuals selected that answer in EqualityAnswers[].

Initially, the approach was to iterate through genderList[] and filter EqualityAnswers[].Gender.AnswerKey to obtain the count.

The challenge lies in assigning this data to an array of ResourceList.

export class ResourceList {
    Name: string;
    Count: number;
}

This array would be named genderCountList: ResourceList[];

The intention is for genderCountList to appear like this: {name:"female", count:2}, {name:"male", count:5}, {name:"prefer not to say", count: 3}

Subsequently, we can dynamically construct tables using this information, enabling us to add answers at the database level.

The only setback is a mental block preventing me from structuring this effectively.

Answer №1

Thanks to Ricardo's valuable advice, I was able to successfully implement this solution.

 retrieveGenderListWithCount(): void {
        var self = this;
        this.genderList.map(function (item, index) {

            var gender = new ResourceList();
            gender.Name = item.Description;
            gender.Count = self.equalityData.filter(x => x.Gender.AnswerKey === item.AnswerKey).length;

            self.genderCountList.push(gender);

            return item;
        });
    }

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

Timestamps are no longer recognized in Highstock charts once data has been added

In my highstock chart, I am pulling data from a REST api and everything appears correct. However, there is no data available between 19:00 and 05:00. I would like this absence of data to be reflected in the chart without cropping out that time span from th ...

Adding values to Firebase Realtime Database using Angular: A step-by-step guide

I'm looking to integrate Firebase Realtime Database with Angular in order to add values. Can anyone provide guidance on how to achieve this integration? Thanks in advance! ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...

Starting a checkbox group with values based on total number

I am facing a challenge with a group of checkboxes that have values assigned as 1,2,4,8,16,32,64. Each number corresponds to a day of the week (e.g. Sunday, Monday etc...) The total value of the checkbox group is calculated as the sum of the selected chec ...

Tips on how to properly handle Promises in a constructor function

My Angular Service is currently making http requests, but I am looking to retrieve headers for these requests from a Promise. The current setup involves converting the promise to an Observable: export class SomeService { constructor(private http: HttpCl ...

Errors detected while attempting to install dependencies using pnpm: modules unspecified

I recently decided to experiment with using pnpm instead of npm for my new projects, but I've encountered an issue. Let's take my nuxt project as an example. First, I set up my project using the command: pnpx nuxi init my-project Then, I insta ...

When initiating an Ionic project, you may notice a repeated message in the terminal saying, "[INFO] Waiting for connectivity with npm..."

I'm in the process of setting up a new Ionic project along with all the necessary dependencies. However, whenever I try to execute the command "ionic serve," I keep getting stuck at the continuous display of the message "[INFO] Waiting for connectivit ...

Avoid waiting in an asynchronous function using a for loop in Angular 12

I am currently working on an asynchronous function that is nested inside a loop. The function iterates through the loop to identify the image name and then uses the await keyword to request the URL from the getDownloadURL() function, which is a function ...

The error message "The specified type '(key: String, value: Any)' does not contain any subscript members" is being displayed

I am currently navigating through an array of dictionaries using this particular code snippet. if let users = object["usersList"] as? [Any] { for user in users as! [String : Any] { print(user["id"]) } } Each dictionary in the array contai ...

Encountering a NameError while attempting to append an element to an array

Struggling to add a new element of type TVector to the array vec_list is causing me some trouble. Each time I try to add a new element, I encounter an error at @vec_list << TVector.new(input[2...input.length]) The error message that pops up reads, ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

How can we use React.js to redirect upon submitting a form?

Hello everyone. I've created an app where users can create posts. As the owner of a post, you have the ability to delete it by clicking on a delete button, which triggers a modal to confirm deletion. However, I'm facing an issue with redirecting ...

Listen for incoming data from the client in the form of an ArrayBuffer

I have been utilizing the ws library within nodejs to develop a small cursor lobby where players can interact. I have managed to utilize the server to send ArrayBuffers with bit streams to the client and successfully decode them. However, I am encountering ...

Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet: export function buildRoutes(options: any, router: Router, roles: string[]): Routes { const lazyRoutes: Routes = Object.keys(options) ...

Utilize the prototype feature from a versatile source

Can a class with a generic like class Foo<A> {} access A's prototype or use a typeguard on A, or perform any kind of logic based solely on A's type - without being given the class, interface, or instance to Foo's constructor (e.g. when ...

Creating a Typescript Interface for Custom Tooltips in Recharts

Although I am still new to Typescript, I am attempting to customize the Tooltip content for my Recharts chart in a React app using Typescript. The @types/recharts package has already been installed as part of the devDependencies. However, upon defining th ...

What is the best way to access the information in a different cell when the corresponding column in the range contains the same variation?

I have a spreadsheet with the following cell contents: Sheet1 A2: "tips for making the perfect cup of coffee" A3: "how to train your puppy" I am trying to create a formula that looks at a range in another sheet (Sheet2!A2:B) and returns the first matchi ...

A data type representing a specific category rather than a specific object

My job involves working with Sequalize models, which are essentially classes. Upon registration, these models are populated with some data that needs to be stored. To accomplish this, I store them in a list. However, when retrieving a model into a variab ...