Cami Rodriguez - 4 years ago 123
Javascript Question

# How to create an incidence array from random array objects?

Given the following:

``````var dataSource = [
{X: 0, Y: 0, ApiKey: "Something"},
{X: 100, Y: 0, ApiKey: "Something"},
{X: 1500, Y: 200, ApiKey: "Something"},
{X: 1600, Y: 850, ApiKey: "Something"},
{X: 0, Y: 750, ApiKey: "Something"},
{X: 0, Y: 800, ApiKey: "Something"},
];
``````

I need to create a new array indicating from range how many incidents there were:

``````var result = [
{fromX: 0, ToX: 500, incidence: 4},
{fromX: 1500, ToX: 2000, incidence: 2}
];
``````

I created an iterative solution, the problem is when data source have 15000 objects it takes over 8-12 minutes! In Node.js. Anyone know a better solution?

You could give an interval and use a hash table for the calculated interval and the count.

``````var dataSource = [{ X: 0, Y: 0, ApiKey: "Something" }, { X: 100, Y: 0, ApiKey: "Something" }, { X: 1500, Y: 200, ApiKey: "Something" }, { X: 1600, Y: 850, ApiKey: "Something" }, { X: 0, Y: 750, ApiKey: "Something" }, { X: 0, Y: 800, ApiKey: "Something" }],
interval = 500,
grouped = [];

dataSource.forEach(function(a) {
var key = Math.floor(a.X / interval);
if (!this[key]) {
this[key] = { fromX: key * interval, toX: (key + 1) * interval, incidence: 0 },
grouped.push(this[key]);
}
this[key].incidence++;
}, Object.create(null));

console.log(grouped);``````

With interval for `X` and `Y`.

``````var dataSource = [{ X: 0, Y: 0, ApiKey: "Something" }, { X: 100, Y: 0, ApiKey: "Something" }, { X: 1500, Y: 200, ApiKey: "Something" }, { X: 1600, Y: 850, ApiKey: "Something" }, { X: 0, Y: 750, ApiKey: "Something" }, { X: 0, Y: 800, ApiKey: "Something" }],
interval = 500,
grouped = [];

dataSource.forEach(function(a) {
var keyX = Math.floor(a.X / interval),
keyY = Math.floor(a.Y / interval),
key = keyX + '|' + keyY;
if (!this[key]) {
this[key] = {
fromX: keyX * interval,
toX: (keyX + 1) * interval,
fromY: keyY * interval,
toY: (keyY + 1) * interval,
incidence: 0
},
grouped.push(this[key]);
}
this[key].incidence++;
}, Object.create(null));

console.log(grouped);``````
``.as-console-wrapper { max-height: 100% !important; top: 0; }``

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