'Filter array of specific objects

How to use filter or forEach in javascript to output only the objects whithout parentId and the objects with only the first level of parentId.

Should output objects with ids: 1681, 1682, and 1683.

Should not output objects with ids: 1685, 1686 and 1687.

array = [ {
                    "id": 1681,
                    "label": "1",
                    "url": "page1",
                },
                {
                    "id": 1682,
                    "label": "2",
                    "url": "page1",
                },
                {
                    "id": 1683,
                    "label": "a",
                    "url": "page1",
                    "parentId": 1681,
                },
                {
                    "id": 1685,
                    "label": "aa",
                    "url": "page1",
                    "parentId": 1683,
                },
                {
                    "id": 1686,
                    "label": "aaa",
                    "url": "page1",
                    "parentId": 1683,
                },
                {
                    "id": 1687,
                    "label": "aaaa",
                    "url": "page1",
                    "parentId": 1683,
                }
]

Something like this...

array.filter(({item}) => !item.parentId ? item.id : item.parentId)


Solution 1:[1]

We have to save the information if we already found a parentId from inside the filter function. A handy way to do this is by using the prefix operator ++ on a counter. This way we get around an explicit, long assignment with =. Instead we make it before.

Additionally with destructuring assignment we can extract the parentId comfortably of the array items and write a really short filter:

array=[{id:1681,label:"1",url:"page1"},{id:1682,label:"2",url:"page1"},{id:1683,label:"a",url:"page1",parentId:1681},{id:1685,label:"aa",url:"page1",parentId:1683},{id:1686,label:"aaa",url:"page1",parentId:1683},{id:1687,label:"aaaa",url:"page1",parentId:1683}];

window.parentIdCount = 0;
window.filtered =

    array.filter(({parentId}) => !parentId || ++parentIdCount <= 1)


console.log(filtered)

Solution 2:[2]

Something like this ought to work:

const result = array.filter(object => object.parentId === undefined);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cachius
Solution 2 Toby T