I’m doing some form of data visualization learning for 180 days because I need to #JFDI.
See post explaining how and why I’m doing this.
Code Learning:
Three Takeaways:
- You can use native array functions to perform left outer joins.
- eg. articles.forEach(function(article) {
var result = brands.filter(function(brand) {
return brand.id === article.brand_id;
});
delete article.brand_id
article_brand = (result[0] !== undefined) ? result[0].name : null;
});
- eg. articles.forEach(function(article) {
- Joining more than one attribute example
- innerArray.filter(function(innerArrayItem) {
return innerArrayItem.idA === outerArrayItem.idA &&
innerArrayItem.idB === outerArrayItem.idB;
});
- innerArray.filter(function(innerArrayItem) {
- Generic Efficent Approach
function join(lookupTable, mainTable, lookupKey, mainKey, select) {
var l = lookupTable.length,
m = mainTable.length,
lookupIndex = [],
output = [];
for (var i = 0; i < l; i++) { // look through l items
var row = lookupTable[i];
lookupIndex[row[lookupKey]] = row;
}
for (var j = 0; j < m; j++) { look through m items
var y = mainTable[j];
var x = lookupIndex[y[mainKey]]; // get corresponding row from lookupTable
output.push(select(y, x)); // select only columns you need
}
return output;
}- eg. var result = join(brands, articles, “id”, “brand_id”, function(article, brand) {
return {
id: article.id,
name: article.name,
weight: article.weight,
price: article.price,
brand: (brand !== undefined) ? brand.name: null
};
});
- eg. var result = join(brands, articles, “id”, “brand_id”, function(article, brand) {
Leave a Reply