鉴于以下情况:
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"},
];
我需要创建一个新数组,从范围中指示发生了多少事件:
var result = [
{fromX: 0, ToX: 500, incidence: 4},
{fromX: 1500, ToX: 2000, incidence: 2}
];
我创建了一个迭代解决方案,问题是当数据源有 15000 个对象时需要 8-12 分钟!在 Node.js 中。有人知道更好的解决方案吗?
最佳答案
您可以给出一个间隔并使用哈希表计算间隔和计数。
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);
X
和 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; }
关于javascript - 如何从随机数组对象创建关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41628413/