繁体   English   中英

如何将缺失值添加到两个关联的数组? (JavaScript的)

[英]How to add missing values to two associated arrays? (JavaScript)

我有两个数组:

  1. category.data.xAxis // containing: ["0006", "0007", "0009", "0011", "0301"]
  2. category.data.yAxis // containing: [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24]

如何获取最大长度,比如DATAPOINT_LENGTH_STANDARD = 540并在xAxis数组中填写每个缺少的基于数字的字符串? 以便:

  1. 生成的xAxis数组将从“0000”读取到“0540”(或者无论标准长度是多少)
  2. 关联的yAxis索引将保持连接到原始xAxis数据点(即“0006”到6.31412)
  3. 每个新创建的xAxis数据点都有一个关联的yAxis值为0(因此新创建的“0000”xAxis条目在yAxis中的索引0处包含0)

可以假设xAxis值字符串已经从最低到最高排序。

编辑

我的问题的清晰度是为了帮助社区找到更直接的答案,但我认为准确性给出了一个家庭作业问题。 响应评论,我的原始尝试,没有正确操纵x轴并保持正确的索引:

let tempArray = categoryObject.data.xAxis;
let min = Math.min.apply(null, tempArray);
let max = Math.max.apply(null, tempArray);
while (min <= max) {
  if (tempArray.indexOf(min.toString()) === -1) {
      tempArray.push(min.toString());
      categoryObject.data.yAxis.push(0);
  }
  min++;
}
console.log(tempArray);
console.log(categoryObject.data.yAxis);

 let xAxis = ["0006", "0007", "0009", "0011", "0301"] let yAxis = [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24] const DATAPOINT_LENGTH_STANDARD = 540 // This assumes at least one data point let paddedLength = xAxis[0].length // Creates a new array whose first index is 0, last index is // DATAPOINT_LENGTH_STANDARD, filled with 0s. let yAxis_new = new Array(DATAPOINT_LENGTH_STANDARD + 1).fill(0) // Copy each known data point into the new array at the given index. // The + before x parses the zero-padded string into an actual number. xAxis.forEach((x, i) => yAxis_new[+x] = yAxis[i]) // Replace the given array with the new array. yAxis = yAxis_new // Store the padded version of the index at each index. for (let i = 0; i <= DATAPOINT_LENGTH_STANDARD; ++i) { xAxis[i] = ('' + i).padStart(paddedLength, '0') } console.log(xAxis) console.log(yAxis) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM