【问题标题】:How to add missing values to two associated arrays? (JavaScript)如何将缺失值添加到两个关联的数组? (JavaScript)
【发布时间】:2019-11-06 17:16:53
【问题描述】:

我有两个数组:

  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 条目将在索引 0 处的 yAxis 中包含 0)

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

编辑

我的问题的明确性是为了帮助社区找到更直接的答案,但我认为准确度看起来像是一个家庭作业问题。为了响应 cmets,我最初的尝试,它没有正确操纵 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);

【问题讨论】:

  • 这不是作业问题,我会更新我的帖子,用我的一些尝试来更新我的帖子。

标签: javascript arrays typescript


【解决方案1】:

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)

【讨论】:

  • 这确实是正确的代码,我不确定你为什么被否决。 cmets 和关闭投票似乎有点敌意。我的假设是有人不认为你应该帮助我,或者你的帖子没有包含任何解释。可能是后者,所以我建议添加一些 cmets 来解释重要的行。如果您添加上述 cmets,我将接受此答案,感谢您的帮助。
  • 我添加了请求的 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多