I have a set of numbers that display as follows:
var data = "615:415,600:400,600:400,300:300"
Each number represents the x / y coordinate, and I would like to add a value next to each, which is calculated based on the frequency of the number within the range.
So, I would like to be able to compare each value with everyone else in this line, and from this the following functions are executed:
- Remove the number from the line if it is a duplicate and add: 1
- If x / y numbers range from 15 to any other number, add: 1
- If there are no matches, add: 0
- Include array
Thus, using the data string, it will be converted to:
var data = "615:415:1, 600:400:2, 300:300:0"
I try to do this using the reducer function, but I'm mostly afraid in step 2. I hope someone can help?
Thanks - Code + Plunk below!
http://plnkr.co/edit/zPW1844cLnUFAlEI77jq?p=preview
var result = [];
var data = "615:415,600:400,600:400,300:300"
var count = 0;
var reducer = function(p, c, i, a) {
if (p && p !== c) {
var _t = p.split(":");
result.push({
x: _t[0],
y: _t[1],
value: count
});
count = 0;
if (i === a.length - 1) {
_t = c.split(":");
result.push({
x: _t[0],
y: _t[1],
value: count
});
}
}
else {
count++;
}
return c
}
data.split(',').sort().reduce(reducer);
console.log(result)
Hide result