Arnab Arnab - 2 years ago 96
Javascript Question

getting distinct values from array of arrays in Javascript

My data is in the following format..

var data= [['typeName', 'valueName'], ['type1', 'value1'],
['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]

I wish to transform the above data to data as below..

var resultdata=[{'typeName':'type1','valueName':['value1','value2']},

Basically I pick up distinct 'typeName' values and then group 'valueName' values by 'typeName' values.

I would preferably use only knockoutjs, lodash or underscorejs as my soln already uses them but I'm open to other solutions as well..

All help is sincerely appreciated


Answer Source

I think this solution using underscore should do the trick:

var result= _.chain(data)
    .groupBy( value => value[0])
    .map( (value,key) => ({ [data[0][0]]: key, [data[0][1]]:, val => val[1])}))

This solution uses rest to skip the first item in the data array (the type descriptors). The array is then grouped by the first value in the array (the type) and the mapping returns the grouping in the required form using es6 object initializer notation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download