arraysangulartypescriptangular15

Rewrite A Code Snippet Instead of For Loop


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[i]?.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));
}

Solution

  • I had to speculate your input data a bit, as this was not provided in the question.

    Using map() to convert (map) the items:

    const userPermissionsGroups = [
      {
        groupId: 660,
        newArrGroups: []
      }
    ];
    
    const items = [
     {id: 648302},
     {id: 648301}
    ];
    
    const newItems = items.map(item => {
      return {
        id: item.id,
        newArrGroups: [...userPermissionsGroups]
      };
    });
    
    console.log(JSON.stringify(newItems, undefined, 2));