如何在两个相关数组中添加缺失值?(JavaScript)

3
我有两个数组:
1. category.data.xAxis // 包含:["0006", "0007", "0009", "0011", "0301"] 2. category.data.yAxis // 包含:[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条目将在索引0处包含yAxis值为0)。
可以假设xAxis值字符串已经按升序排列。
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);

这不是一个作业问题,我会更新我的帖子,并附上一些我尝试过但没有达到我要求的内容。 - About7Deaths
1个回答

4

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)


这确实是正确的代码,我不确定为什么你被踩了。评论和关闭投票似乎有点敌对。我的假设是要么有人觉得你不应该帮助我,要么你的帖子没有包含任何解释。很可能是后者,所以我建议添加一些注释来解释重要的行。如果你添加了这些注释,我会接受这个答案,感谢你的帮助。 - About7Deaths
我添加了所请求的注释。 - Mike Stay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接