Published
Edited
Dec 2, 2019
Insert cell
md`# Left join CSV files`
Insert cell
cars = d3.csvParse(`brand_id,name,mpg
1,Mazda RX4,21
1,Mazda RX4 Wag,21
2,Datsun 710,22.8
3,Hornet 4 Drive,21.4
3,Hornet Sportabout,18.7
4,Valiant,18.1
`)
Insert cell
brands = d3.csvParse(`id,name
1,Mazda
2,Datsun
3,Hornet
5,Whatever
`)
Insert cell
//another way to join using a functional approach
cars.map( record => {
let r = record;
r.joinedBrand = brands.filter( b => b.id == r.brand_id );
return r
})

Insert cell
join(brands, cars, "id", "brand_id", function(car, brand) {
return {
brand_id: car.brand_id,
brand_name: (brand !== undefined) ? brand.name : null,
car_name: car.name
};
})
Insert cell
md`---

## Appendix`
Insert cell
d3 = require('d3')
Insert cell
function join(lookupTable, mainTable, lookupKey, mainKey, select) {
var l = lookupTable.length,
m = mainTable.length,
lookupIndex = [],
output = [];
for (var i = 0; i < l; i++) { // loop through l items
var row = lookupTable[i];
lookupIndex[row[lookupKey]] = row; // create an index for lookup table
}
for (var j = 0; j < m; j++) { // loop through m items
var y = mainTable[j];
var x = lookupIndex[y[mainKey]]; // get corresponding row from lookupTable
output.push(select(y, x)); // select only the columns you need
}
return output;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more