如何从随机数组对象创建一个入射数组?

时间:2017-01-13 06:12:32

标签: javascript algorithm performance search

鉴于以下内容:

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.谁知道更好的解决方案?

3 个答案:

答案 0 :(得分:1)

您可以给出一个间隔,并使用哈希表来计算间隔和计数。



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);




XY的间隔。



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; }




答案 1 :(得分:0)

我建议使用D3,因为它优化了一些方法,例如groupby

d3.nest()
    .key(_ => _)
    .rollup(leaves => leaves.length)
    .entries(dataSource.map(_ => _.X / 1500 | 0))
    .map(_ => { return {
        'fromX':_.key * 500,
        'ToX': (1 + _.key) * 500, 
        'incidence': _.values
    }})

答案 2 :(得分:0)

我建议您扩展dataSource数组,因此每次将事件推入dataSource时,都会记录下来。

dataSource = [];
dataSource.ix = [];
dataSource.result = [];
dataSource.push = function(o) {
    if (ix[o.X] !== undefined)
        ix[o.X]++;
    else ix[o.X] = 1;
    Array.prototype.push.call(this, o);
};
dataSource.calculate = function(a, b) {
    var i, r = {
        fromX: a,
        ToX: b,
        incidence: 0
    };
    for (i = a; i <= b; i++) {
        if (this.ix[i])
            r.incidence += this.ix[i];
    }
    this.result.push(r);
};