How to loop and concat second array list if exist using Javascript

Viewed 48
 transaction =[
          {
            "details": [
              {
                "type": "1",

              },
              {
                "type": "2",

              }
            ],
            "list": {
              "number": "30",

            }
          },
          {
            "details": [
              {
                "type": "3",

              },
              {
                "type": "4",

              }
            ],
            "list": {
              "number": "30",

            }
          }
        ]

expected output after combining 2 array in a loop:

{
  "details": [
    {
      "type": "1",

    },
    {
      "type": "2",

    },
    {
      "type": "3",

    },
    {
      "type": "4",

    }
  ]
}

Is there any way to check if second array exist and then concat the second array in a loop.I tried to loop and iterate using map and concat the array list any suggestion would be appreciated thanks

map((activity:{ details: any; list: any; }) => { 
                const data = activity.details!.concat(activity
                    .filter((activity) => activity.details.includes(activity.details)));
                  console.log(data);
            })
1 Answers

You can use reduce() and spread operator to create a combined 1D array. Before adding the new details array to final result filter() by checking that all the previous types are differ using every()

const transaction =[
          {
            "details": [
              {
                "type": "1",

              },
              {
                "type": "2",

              }
            ],
            "list": {
              "number": "30",

            }
          },
          {
            "details": [
              {
                "type": "3",

              },
              {
                "type": "4",

              }
            ],
            "list": {
              "number": "30",

            }
          }
        ]
const res = transaction.reduce((ac, a) => 
              [...ac, ...a.details.filter(x => ac.every(n => n.type !== x.type))], []
            );
console.log(res)

Related