Published
Edited
Mar 3, 2018
2 stars
Insert cell
Insert cell
Insert cell
data=[{"name":"A","location":"USA"},
{"name":"B","location":"USA"},
{"name":"C","location":"Japan"},
{"name":"D","location":"China"},
{"name":"E","location":"USA"},
{"name":"F","location":"USA"},
{"name":"G","location":"Canada"},
{"name":"H","location":"Russian"}]
Insert cell
md`## Filter with Array.filter`
Insert cell
{
const svg = d3.select(DOM.svg(200,200))

// preprocess the data with Array.filter
const filtered = data.filter((d)=>{return d.location !== 'USA';})

const circles = svg.selectAll('circle').data(filtered)

const circlestages = svg.selectAll('text')
.data(filtered)


circles.enter()
.append('circle')
.attr('cx', 10)
.attr('cy', (d,i)=> 10 + i*20)
.attr('r', 5)
.attr('fill', 'red');
circlestages.enter()
.append('text')
.attr('x', 15)
.attr('y', (d,i)=> 12 + i*20)
.attr('font-size',10)
.text((d,i)=>{
return "name: "+ d.name +" , "+"location: " + d.location ;
})
return svg.node()
}
Insert cell
md`## Filtering on the d3.selection.filter`
Insert cell
{
const svg = d3.select(DOM.svg(200,200))

const circles = svg.selectAll('circle').data(data);

const circlestages = svg.selectAll('text')
.data(data)




circles.enter()
.append('circle')
.attr('cx', 10)
.attr('cy', (d,i)=> 10 + i*20)
.attr('r', 5)
.attr('fill', 'red');
circlestages.enter()
.append('text')
.attr('x', 15)
.attr('y', (d,i)=> 12 + i*20)
.attr('font-size',10)
.text((d,i)=>{
return "name: "+ d.name +" , "+"location: " + d.location ;
})

// filter after the element created
svg.selectAll('circle').filter((d,i)=> d.location === 'USA').remove();
svg.selectAll('text').filter((d,i)=> d.location === 'USA').remove();
return svg.node()
}
Insert cell
md`## Filtering on the d3.selection directly`
Insert cell
{
const svg = d3.select(DOM.svg(200,200))

const circles = svg.selectAll('circle').data(data);

const circlestages = svg.selectAll('text')
.data(data)




circles.enter()
.append('circle')
.attr('cx', 10)
.attr('cy', (d,i)=> 10 + i*20)
.attr('r', 5)
.attr('fill', 'red');
circlestages.enter()
.append('text')
.attr('x', 15)
.attr('y', (d,i)=> 12 + i*20)
.attr('font-size',10)
.text((d,i)=>{
return "name: "+ d.name +" , "+"location: " + d.location ;
})
// filter the element using d3.select()
svg.selectAll('text').select((d,i,g)=> {return d.location === 'USA'?g[i]:null}).remove();
svg.selectAll('circle').select((d,i,g)=> {return d.location === 'USA'?g[i]:null}).remove();

return svg.node()
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more