Exploring ways to enhance the functionality of JavaScript using the underscore library. Any ideas on how to elevate this code from imperative to more functional programming?
In the provided array, the first value in each pair represents a "bucket" and the second value is an item. The goal is to iterate through this data and generate a list of unique items in each bucket.
var data = [
['A',1],
['A',1],
['A',1],
['A',2],
['B',1],
['B',2],
['B',2],
['B',4],
['C',6],
['D',5]
];
// Expected output:
// {
// A: [1,2],
// B: [1,2,4],
// C: [6],
// D: [5]
// }
_.chain(data)
.groupBy(function (pair) {
var bucket = pair[0];
return bucket;
})
.mapObject(function (values, key) {
var result = _.chain(values)
.map(function (pair) {
return pair[1]
})
.uniq()
.value();
return result;
})
.value();