You could get the pathes first and then filter the given key, if it is more than in two pathes, then filter out this value.
function filter(source, targets) {
function getPath(array, target) {
return array.reduce((r, { key, children }) => {
var temp;
if (key === target) return r.concat(key);
if (children) {
temp = getPath(children, target);
if (temp.length) return r.concat(key, temp);
}
return r;
}, [])
}
var temp = targets.map(k => getPath(source, k));
return targets.filter(v => !temp.some((c => a => a.includes(v) && ++c)(-1)));
}
var array = [{ key: 1, title: 'aa', children: [{ key: 2, title: 'bb', children: [{ key: 3, title: 'cc', children: [{ key: 5, title: 'ee', children: [{ key: 6, title: 'ff' }, { key: 7, title: 'gg' }, { key: 8, title: 'hh' }] }] }, { key: 4, title: 'dd', }] }] }],
result = filter(array, [1, 2, 3, 4, 8]);
console.log(result);
solved Javascript array filter child! [closed]