Day 102 of 180 Days of Data Viz Learning #jfdi

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:

Combining Data

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;
      });
  • Joining more than one attribute example
    • innerArray.filter(function(innerArrayItem) {
      return innerArrayItem.idA === outerArrayItem.idA &&
      innerArrayItem.idB === outerArrayItem.idB;
      });
  • 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
      };
      });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s