Rewrite A Code Snippet Instead of For Loop

Discussão em 'Angular' iniciado por user8512043, Janeiro 10, 2025.

  1. user8512043

    user8512043 Guest

    I've the following data format in jSon:

    [
    {
    "id": 648302,
    "newArrGroups": [
    {
    "groupId": 660,
    "newArrGroups": []
    }
    ]
    },
    {
    "id": 648301,
    "newArrGroups": [
    {
    "groupId": 660,
    "newArrGroups": []
    }
    ]
    }
    ]


    This is how I added the data using a for loop:

    const result: any = [];

    for (let i = 0; i < this.items.length; i++) { //item is an array with the id element
    result.push({ id: this.items?.id, newArrGroups: this.userPermissionsGroups });
    }


    So what it does, it iterates each element from the items array and add the group to each element of the items array as new array shown in the data sample. There is no relationship, so if there's any existing group then it gets added to each element of the items array. I was trying to do it in a better way, say with map. Is it possible rather than a for loop something as follows (I know, this would generate a different result set)?

    function addArrayToEachElement(originalArray: number[], arrayToAdd: number[]): number[][] {
    return originalArray.map(element => [element].concat(arrayToAdd));
    }

    Continue reading...

Compartilhe esta Página