【问题标题】:Break large array into 10 batches (regardless of batch size). TypeScript/Javascript将大数组分成 10 个批次(无论批次大小)。打字稿/Javascript
【发布时间】:2022-10-04 22:47:17
【问题描述】:

我有一个逻辑问题,我被困住了,可以使用一些帮助。我认为这对我来说通常很容易,但在佛罗里达州的伊恩飓风过后,我有点脑筋急转弯。

我正在 Azure 地图上绘制渐变线。我的 GPS 服务会为沿途的这些点返回大量坐标(纬度/经度)和相关数据。

我发现对于更长的路线,Azure 地图最多只能接受 lineLayer 方法的 10 个坐标。

我的问题更多的是逻辑。我有一个坐标数组,可能有 4000 多个项目。有时更多,有时更少,具体取决于所选路线的长度。

我需要将 4000 多个项目分成 10 个块,从那里,我将取出 10 个中的第一个项目并用它来绘制我的数据点。

因此,对于 4000 个项目,我的分块数组大小将为 400。2000 个项目将是 200、100、10、50 将是 5,等等。如果最后一个块中有溢出,那很好。

//This is the top temperature
this.finalTemp = 75

//I need to break points into 10 chunks so the Azure maps lineLayer expression can handle it.
for (var i = 0; i < points.length; i++) {
  let temperatureAtPoint = points[i].temperature //22.0 - this will usually increase as we iterate through.
  let progressValue: number = pointTemp / this.finalTemp;

  //this progressValue will be used to generate a color that is plotted on the map (I have that working)

}

对于我的生活,我无法弄清楚这一点,并认为我会跳到这里看看是否有人可以让我直截了当。我只需要一个打字稿或 Javascript 示例。

谢谢!

【问题讨论】:

标签: javascript typescript azure-maps


【解决方案1】:

以下应该足够了

function sliceIntoChunks(arr, chunkSize) {
    const res = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        const chunk = arr.slice(i, i + chunkSize);
        res.push(chunk);
    }
    return res;
}

// the remainder is important because if not divisible then it would be a float number, we can safely omit it
let chunkSize = (points.length + (points.length % 10)) / 10
const chunkedArray = sliceIntoChunks(points, chunkSize)

This article 总结得很好。

【讨论】:

  • 我编辑了这个,因为我在第一次迭代中忘记了除以 10!现在它应该可以正常工作了
猜你喜欢
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 2021-09-21
  • 2019-04-22
相关资源
最近更新 更多