I'm trying to convert an array of strings into an object for which each member uses the string for a key, and initializes the value to 0. (Classic accumulator for Word Count, right?)
Here's the style of the input data:
%dw 2.0
output application/dw
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
To get the accumulator, I need a structure in this style:
var histogram_acc = {
"t.me" : 1,
"thewholeshebang.com" : 1,
"thegothicparty.com" : 2,
"windowdressing.com" : 1
}
My thought was that this is a slam-dunk case for reduce(), right?
So to get the de-duplicated list of hosts, we can use this phrase:
hosts distinctBy $
Happy so far. But now for me, it turns wicked.
I thought this might be the gold:
hosts distinctBy $ reduce (ep,acc={}) -> acc ++ {ep: 0}
But the problem is that this didn't work out so well. The first argument to the lambda for reduce() represents the iterating element, in this case the endpoint or address. The lambda appends the new object to the accumulator.
Well, that's how I hoped it would happen, but I got this instead:
{
ep: 0,
ep: 0,
ep: 0,
ep: 0
}
I kind of need it to do better than that.