Created
March 1, 2020 00:39
-
-
Save yojona/bc0aaa1bb75e3ee3b4bff62367194313 to your computer and use it in GitHub Desktop.
JS recursive children filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackblitz.com/edit/recursive-filter-prop?file=index.ts | |
// perf: https://jsbench.me/8cjrlaine7/1 | |
function flatFilter(nestedProp, compareKey, compareId, arr) { | |
return arr.filter(o => { | |
const keep = o[compareKey] != compareId; | |
if (keep && o[nestedProp]) { | |
o[nestedProp] = flatFilter(nestedProp, compareKey, compareId, o[nestedProp]); | |
} | |
return keep; | |
}); | |
} | |
const ARRAY = [ | |
{ | |
id: 1, | |
children: [ | |
{ | |
id: 2, | |
children: [ | |
{ | |
id: 3, | |
}, | |
{ | |
id: 4, | |
}, | |
], | |
}, | |
{ | |
id: 5, | |
children: [ | |
{ | |
id: 3, | |
}, | |
], | |
}, | |
], | |
}, | |
]; | |
console.log(JSON.stringify(flatFilter('children', 'id', 3, ARRAY), null, 2)); | |
/* result | |
[ | |
{ | |
id: 1, | |
children: [ | |
{ | |
id: 2, | |
children: [ | |
{ | |
id: 4, | |
}, | |
], | |
}, | |
{ | |
id: 5, | |
children: [], | |
}, | |
], | |
}, | |
]; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment