簡體   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