Chris Chris - 6 months ago 33
Javascript Question

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

I'd like to transform the below dataset array into a different format. Currently, each dictionary in the array has a 'count', 'fruit', and 'first name'. I'd like to create a new dictionary for each distinct first name and values that first name has for each 'fruit' type.

For example, see below for some 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 for this dataset that the categories are ['apple', 'banana', 'cherry']

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


You could use a hash table for the name reference and an object for the rigth index for 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: () { return 0; }) };
    this[a.first_name].data[cat[a.fruit]] += a.count;
}, Object.create(null));