Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter and Combine Nested Array in ES6

I need to combine the gid and subGroups and output it into an array of strings without duplication. My problem now is that it only gets the first level.

const oldGroup = [
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "SFO",
        "subGroups": []
    },
    {
        "gid": "LAX",
        "subGroups": [
            "LGA"
        ]
    }
]

const newGroup = [...new Set(oldGroup.map((group) => group.gid))]

console.log(newGroup)
like image 205
Joseph Avatar asked Apr 20 '26 07:04

Joseph


2 Answers

There are several ways to achieve this, here is one with .reduce():

const oldGroup = [
    { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
    { "gid": "JFK", "subGroups": [ "SFO", "LAX" ] },
    { "gid": "SFO", "subGroups": [] },
    { "gid": "LAX", "subGroups": [ "LGA" ] }
];

const newGroup = Object.keys(oldGroup.reduce((acc, obj) => {
  acc[obj.gid] = true;
  obj.subGroups.forEach(name => { acc[name] = true; } );
  return acc;
}, {}));

console.log(newGroup)

Explanation:

  • The .reduce() has two parameters:
    • a function parameter with two options acc, obj. The former is the accumulator that keeps track of the data needed, the latter is the array item object
    • an initial setting, and empty {} object in our case
  • Object.keys() is applied on the accumulated data
like image 69
Peter Thoeny Avatar answered Apr 22 '26 21:04

Peter Thoeny


With .flatMap instead of .map, return an array in the callback - the .gid value, and also spread in the .subGroups array.

const oldGroup = [
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "JFK",
        "subGroups": [
            "SFO",
            "LAX"
        ]
    },
    {
        "gid": "SFO",
        "subGroups": []
    },
    {
        "gid": "LAX",
        "subGroups": [
            "LGA"
        ]
    }
]

const newGroup = [...new Set(oldGroup.flatMap((group) => [group.gid, ...group.subGroups]))]

console.log(newGroup)
like image 35
CertainPerformance Avatar answered Apr 22 '26 22:04

CertainPerformance