How to group and transform dictionary array on a certain key attribute to a different format with javascript (functional programming)? -


i'd transform below dataset array different format. currently, each dictionary in array has 'count', 'fruit', , 'first name'. i'd create new dictionary each distinct first name , values first name has each 'fruit' type.

for example, see below input data

var input_data = [{"count":1,"fruit":"apple","first_name":"abe"},{"count":1,"fruit":"apple","first_name":"bob"},{"count":10,"fruit":"banana","first_name":"bob"},{"count":5,"fruit":"cherry","first_name":"abe"}] 

we know dataset categories ['apple', 'banana', 'cherry']

var desired_output =  [{name: 'abe',data:[1,0,5]}, {name: 'bob',data:[1,10,0]}] 

you use hash table name reference , object rigth index counting.

var input_data = [{"count":1,"fruit":"apple","first_name":"abe"},{"count":1,"fruit":"apple","first_name":"bob"},{"count":10,"fruit":"banana","first_name":"bob"},{"count":5,"fruit":"cherry","first_name":"abe"}],      categories = ['apple', 'banana', 'cherry'],      cat = {},      result = [];    categories.foreach(function (a, i) { cat[a] = i; });  input_data.foreach(function (a) {      if (!this[a.first_name]) {          this[a.first_name] = { name: a.first_name, data: categories.map(function () { return 0; }) };          result.push(this[a.first_name]);      }      this[a.first_name].data[cat[a.fruit]] += a.count;  }, object.create(null));  console.log(result);


Comments