generate a fresh array with matching keys

Here is an example array:

subjectWithTopics = [
  {subjectName:"maths", topicName : "topic1 of maths " },
  {subjectName:"maths", topicName : "topic2 of maths " },
  {subjectName:"English", topicName : "topic1 of English " },
  {subjectName:"English", topicName : "topic2 of English " },
  {subjectName:"English", topicName : "topic3 of English " },
]

I am looking to iterate through this array using *ngFor in angular :

  • Maths:

    Topic 1 of Maths

    Topic 2 of Maths

  • English

    Topic 1 of English

    Topic 2 of English

    Topic 3 of English

Desired output:

subjectWithTopics =[
{"SubjectName" : "Maths",
        "topicName" : [
          {
            topic1 of Maths
          },
          {
           topic 2 of Maths
          },
        ]
},
 {"SubjectName" : "English",
        "topicName" : [
          {
            topic 1 of English
          },
          {
            topic 2 of English
          },
          {
            topic 3 of English
          }
        ]
}
]

Answer №1

One effective way to achieve this is by utilizing the Array.prototype.reduce method:

ts

subjectWithTopics = [
  { subjectName: "maths", topicName: "topic1 of maths " },
  { subjectName: "maths", topicName: "topic2 of maths " },
  { subjectName: "English", topicName: "topic1 of English " },
  { subjectName: "English", topicName: "topic2 of English " },
  { subjectName: "English", topicName: "topic3 of English " },
];

desiredResult: { SubjectName: string; topics: any[] }[];

ngOnInit() {
  const groups = this.subjectWithTopics.reduce((acc, cur) => {
    (acc[cur.subjectName] = acc[cur.subjectName] || []).push(cur.topicName);

    return acc;
  }, {});
  this.desiredResult = Object.keys(groups).map(key => ({ SubjectName: key, topics: groups[key] }))
}

html

<ul *ngFor="let item of desiredResult">
  <li>
    {{ item.SubjectName }}
    <ol>
      <li *ngFor="let topic of item.topics">
        {{ topic }}
      </li>
    </ol>
  </li>
</ul>

Check out an example on Ng-run

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 value calculated by Auto does not display as a valid number in Angular 8 until it has been manually edited

Having an issue with a form submission for invoicing. The total value field, which is auto-calculated based on quantity and unit price, does not show up as numeric data in the backend onSubmit event unless I manually interact with it by adding something ...

problem encountered while attempting to drag and drop list elements on a web application utilizing dhtmlx 5.0 and wijmo grid

My web application utilizes Dhtmlx 5.0, Wijmo grid, and Typescript. One feature of the app is a dialog box that displays a list of items which can be rearranged using drag and drop functionality. This feature works without any issues on Windows PCs but enc ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Tips for securely encrypting passwords before adding them to a database:

While working with Nest.Js and TypeORM, I encountered an issue where I wanted to hash my password before saving it to the database. I initially attempted to use the @BeforeInsert() event decorator but ran into a roadblock. After some investigation, I disc ...

What is the best method to obtain access to the controls of an item within FormArray?

My goal is to assign an invalid class to the parent div of each input based on its validity status. In the form, I can control the input fields like this: <div class="form-group focus" [ngClass]="!recipeForm.controls.name.valid ? ...

Nest an array inside another array using a foreach loop

I've successfully created a code that generates two arrays using foreach loop and existing data. Now, I am looking to merge these two arrays into one. Below is the code for the first array : $sql = "SELECT photoprofile,username from photo WHERE usern ...

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

Angular - calculate the total of numerical values within a nested *ngFor loop

Looking to extract numerical values from an array of objects, where each object contains specific data within arrays. I attempted using *ngFor to iterate through the values, but instead of summing them up, they are concatenated together. Here's a brie ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

We are encountering an issue with a missing module: Error: Unable to locate '@angular/flex-layout' in the 'app' directory

Out of nowhere I encountered the following error: Module not found: Error: Can't resolve '@angular/flex-layout' in '\src\app' This issue popped up right after I installed @angular/cdk. To address this error, I reinstal ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

Challenges with image cropping in Angular causing performance problems

Utilizing this specific component for image cropping within an ionic/angular8 project has been causing severe performance issues, leading to unresponsiveness on mobile devices. Interestingly, the desktop version does not encounter any problems and the crop ...

Guidelines for converting an array into checkboxes using React Native with TypeScript

As I embark on my React Native journey, I have chosen to use TypeScript in my project. Currently, I am faced with the challenge of mapping an array into a checkbox. Enclosed below is a snippet from my JSON file: { "stud_name": "Adam", "sex": "male" ...

When an Angular service is created, its properties are not immediately configured

My current task involves testing an Angular (4.1) service that looks like this: @Injectable() export class JobService { private answerSource = new Subject<AnswerWrapper>(); answer$ = this.answerSource.asObservable(); answer(answer: AnswerWra ...

Error message: The tag name "[email protected]" is not valid when attempting to execute npm install

I'm encountering an issue while trying to build my Angular app using Azure Continuous Integration. Right before the build step, there is an npm install process that is failing and generating the following error: Error: Invalid tag name ""<a h ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...

An error occurred due to attempting to access properties of null while trying to read 'useMemo' in a Next.js TypeScript application

Currently engaged in a Next.js 13 project with TypeScript, utilizing the useDrag hook. No errors are being flagged in my Visual Studio Code editor; however, upon attempting to render the page, an error message surfaces. The issue points to a problem with t ...