fatt101 fatt101 - 3 months ago 7
Javascript Question

How to manipulate an array generated from .reduce function into separate key/value pairs? (JavaScript)

I'm struggling to resolve an issue I'm having with .reduce;

Currently, I am iterating through an array to count the number of duplicates as can be seen below;



var data = ['141:150.5', '141:150.5', '141:150.5', '224:297.5','83:351.5','278:434.5','332:182', '332:182','263:135','256:155','256:155','105:65']


var reducer = function(tally, vote) {
if(!tally[vote]){
tally[vote] = 1
} else {
tally[vote] = tally[vote] + 1;
}

return tally;
}

var result = data.reduce(reducer, {});

console.log(result)





What I would like to do is split the output of each item from this array into an object which has 3 key/value pairs.

So taking the first result from the output above
("141:150.5": 3)
I would like to generate the following;

{
value1: 141,
value2: 150.5,
count: 3
},


and so on so forth.

However since the above function doesn't output an array length, it means I cannot iterate through
result
in order to start building the desired objects.

I'm a bit lost here - any help/advice would be much appreciated!

Answer

As commented, you just have to split the key value and process accordingly.

Also, I have taken leisure to update your reduce function.

var data = ['141:150.5', '141:150.5', '141:150.5', '224:297.5', '83:351.5', '278:434.5', '332:182', '332:182', '263:135', '256:155', '256:155', '105:65']

var reducer = function(tally, vote) {
  tally[vote] = (tally[vote] || 0) + 1;
  return tally;
}

var result = data.reduce(reducer, {});

var output = [];
for(var k in result){
  var _t = k.split(":");
  output.push({
    value1: _t[0],
    value2: _t[1],
    count: result[k]
  });
}

console.log(output)

You can also update your reduce function to directly give output like:

var data = ['141:150.5', '141:150.5', '141:150.5', '224:297.5', '83:351.5', '278:434.5', '332:182', '332:182', '263:135', '256:155', '256:155', '105:65']

var count = 1;
var reducer = function(p, c, i, a) {
  if (p && p !== c) {
    var _t = p.split(":");
    result.push({
      value1: _t[0],
      value2: _t[1],
      count: count
    });
    count = 1;
    if (i === a.length - 1) {
      _t = c.split(":");
      result.push({
        value1: _t[0],
        value2: _t[1],
        count: count
      });
    }
  } else {
    count++;
  }
  return c
}

var result = [];
data.sort().reduce(reducer);

console.log(result)