Here's how you can combine several elements from one array and assign them to the first element of another array:

I'm working with an array that looks like this:

public static readonly List: Array<any> = [
    { name: 'CCS', link: 'Dummy link1' },
    { name: 'CCR', link: 'Dummy link2' },
    { name: 'PM', link: 'Dummy link3' },
    { name: 'CM', link: 'Dummy link4' },
    { name: 'JM', link: 'Dummy link5' },
    { name: 'PSM', link: 'Dummy link6' }
];

My goal is to split this array into smaller arrays each containing 3 elements, like so:

ArrayFinal[{
             { name: 'CCS', link: 'Dummy link1' },
             { name: 'CCR', link: 'Dummy link2' },
             { name: 'PM', link: 'Dummy link3' }
           },
           {
             { name: 'CM', link: 'Dummy link4' },
             { name: 'JM', link: 'Dummy link5' },
             { name: 'PSM', link: 'Dummy link6' }
           }]

I've attempted to accomplish this by checking for a modulus of 3 and then creating the new arrays accordingly, but I seem to be facing some issues.

Any guidance or assistance in solving this problem would be greatly appreciated.

UPDATE Here is what I have tried so far:

public func(): any {
    for (let i = 1; i <= Array.List.length; i++) {
        if (i % 3 === 0) {
            this.ArrayFinal[i] = [Array.List[i], Array.List[i - 1], 
            Array.List[i - 2]];
        }
    }

However, it appears to be skipping the first element, and I am struggling to understand why. Any insight on this issue would be incredibly helpful.

Answer №1

I successfully transformed the following list:

List: Array<any> = [
    { name: 'CCS', link: 'Dummy link1' },
    { name: 'CCR', link: 'Dummy link2' },
    { name: 'PM', link: 'Dummy link3' },
    { name: 'CM', link: 'Dummy link4' },
    { name: 'JM', link: 'Dummy link5' },
    { name: 'PSM', link: 'Dummy link6' }
  ];

into this structure:

[ 
  [ 
    { "name": "CCS", "link": "Dummy link1" },
    { "name": "CCR", "link": "Dummy link2" }, 
    { "name": "PM", "link": "Dummy link3" }
  ], 
  [ 
    { "name": "CM", "link": "Dummy link4" }, 
    { "name": "JM", "link": "Dummy link5" }, 
    { "name": "PSM", "link": "Dummy link6" }
  ]
]

Utilizing the provided code snippet below:

from(this.List).pipe(
  bufferCount(3)
).subscribe(x => this.groupedList.push(x));

The from function converts the array into an observable.

The bufferCount(3) method groups three elements at a time.

Whenever three elements are emitted from the observable, they are added to an element of the groupedList array.

You can view the implementation on stackblitz: https://stackblitz.com/edit/angular-buffer-count-deborahk

Answer №2

To achieve this task, you can utilize a combination of slice and splice operations on arrays. Begin by using slice to extract a portion of the source array, then add this portion to the target array using the spread operator (...), and finally use splice to remove the extracted elements from the source array. Continue iterating through the array until all items have been processed.


while (source.length >= 3) {
    target.push({...source.slice(0, 3)});
    source.splice(0, 3);
}

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

Issues with loading style or script files have been encountered when running ng build and ng build --prod

While building my application, I have successfully created the production build. However, when trying to run this version, an error appears in the console stating that style or script files failed to load. The "@angular/cli" version I am using is "~9.1.1" ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

Mongoose TypeScript Aggregation error: is not a valid property of type 'any[]'

Attempting to replace a standard mongo call with an aggregate call. The original code that was functional is as follows: const account = await userModel .findOne({ 'shared.username': username }) .exec(); console.log(account._id) The n ...

Harvesting Angular information using Selenium

Here is some HTML code that can be extracted using a Selenium driver: <td colspan="2"><strong>Owner</strong> <div ng-class="{'owner-overflow' : property.ownersInfo.length > 4}"> ...

Tips on minimizing the vertical size of a mat field housing a mat-select dropdown

I need help reducing the height of a mat field that includes a mat-select in Angular v15. The code is directly from the material components documentation, with no alterations. It consists of a default table and default outline formfield. <mat-form-fi ...

Can a type name be converted into a string representation for use as a template literal type?

Is there a way to retrieve the string representation of a type name in order to return a more concise compile error message from a type function? I came across this solution (unfortunately, the article does not have anchor links so you will need to search ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

When attempting to dispatch an action with switchMap, it fails, while map successfully triggers the

I recently started utilizing ngrx and ngrx/effects. In the code snippet below, I encountered an issue where using switchMap with concatLatestFrom and dispatching an action fails, while using map seems to work perfectly fine. Any idea why? When trying to ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

Tips for eliminating top and bottom spacing in angular material mat-row/mat-cell elements

I am working with an Angular material mat-table where I want to adjust the row height to fit only the text, without any extra space above and below it. I attempted to directly modify the mat-cell like this, but unfortunately, it did not work: <mat-cell ...

An issue arises when trying to access a resolved variable from UI router in a component

I am facing an issue with my UI router state that has a component attached to it: export const exchangeState = { name: 'exchange', url: '/exchange', component: ExchangeMainComponent, resolve: [ { tok ...

Exploring the Integration of Google Maps and Angular Google Places in Angular 2

On my webpage, I am utilizing two components simultaneously: and angular2-google-map-auto-complete from https://www.npmjs.com/package/angular2-google-map-auto-complete. To set the Angular maps key, I have defined it as follows: AgmCoreModule.forRoot({ a ...

Leveraging Fastify's preHandler middleware functionality

Implementing a middleware to validate user authentication before accessing the specified route. Encountering an issue where tokenService inside tokenController is showing as undefined when passing tokenController.authUser as a middleware. However, the met ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

Issue: Unable to resolve all parameters for setupRouter function

I encountered an error stating "Can't resolve all parameters for RouteParams" while setting up a basic app for routing. Here is how my app.module.ts file is structured: import { NgModule } from '@angular/core'; import { BrowserModule ...

Inconsistency with Angular 4 instance variables causes ambiguity within a function

Here is the code snippet: @Component({ selector: 'unb-navbar', templateUrl: './navbar.html' }) export class NavbarComponent implements OnInit { @Input() brand: string; controlador:boolean=false; overlay:string=""; @Input() menu ...

Angular Nested Interface is a concept that involves defining an

Looking for guidance on creating a nested interface for JSON data like this: Any help is appreciated. JSON Structure "toto": { "toto1": [], "toto2": [], "toto3": [], } Interface Definition export interface Itot ...