[英]Javascript - Compare two arrays and add missing items into first array
[英]How to add missing values to two associated arrays? (JavaScript)
我有兩個數組:
category.data.xAxis // containing: ["0006", "0007", "0009", "0011", "0301"]
category.data.yAxis // containing: [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24]
如何獲取最大長度,比如DATAPOINT_LENGTH_STANDARD = 540
並在xAxis數組中填寫每個缺少的基於數字的字符串? 以便:
可以假設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.