Skip to content

Instantly share code, notes, and snippets.

@HollyPony
Created April 28, 2018 12:35
Show Gist options
  • Save HollyPony/3a4f0e53bcaeecfff303f0eeea8d49c0 to your computer and use it in GitHub Desktop.
Save HollyPony/3a4f0e53bcaeecfff303f0eeea8d49c0 to your computer and use it in GitHub Desktop.
Basic search in a multi level tree
export function flat (data) {
return data.reduce((acc, branch) => (!branch.data || branch.data.length === 0)
? acc.concat(branch) // Add the branch to the result if no subNodes
: acc.concat(...flat(branch.data).map(item => ({ // If subNodes, reflat it
...item,
name: `${branch.name}.${item.name}` // Update the names of subNodes to follow the path
}))), [])
}
export function flatSimple (keyword, tree) {
return data.reduce((acc, branch) => (!branch.data || branch.data.length === 0)
? acc.concat(branch) // Add the branch to the result if no subNodes
: acc.concat(...flatSimple(branch.data)), [])
}
export function filterTreeSimple (keyword, tree) {
return flatSimple(tree) // Flat the data
.filter(branch => branch.name.toLocaleLowerCase().includes(keyword.toLocaleLowerCase())) // Do the filter
}
export default function filterTree (keyword, tree) {
return flat(tree) // Flat the data
.filter(branch => branch.name.toLocaleLowerCase().includes(keyword.toLocaleLowerCase())) // Do the filter
}
console.log(filterTree('ni', [{
name: 'Annie',
data: [{
name: 'Paul'
}]
}, {
name: 'Jean',
data: [{
name: 'Fani'
}]
}, {
name: 'Romain'
}, {
name: 'Mami'
}]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment