簡體   English   中英

使用 JavaScript 在每列的數組中查找連續重復的數字

[英]Finding continuous repetition of numbers in an array in each column using JavaScript

我有來自 8 個站點的實時溫度日志用於科學研究。 每當所有 8 個站都獲得數據時,它會被推送到一個 8 列的數組中。

例如下表

  Time1    22  26  18  12  20  15  ..   for 8 stations

  Time2   20  26  15  13  20  18...

  Time3   19  28  17  15  20  16 ...

Time1 是最近的數據標簽... Time2 是前一個等等。

這里 26 在站 #2 中重復了 2 次

 20 is repeated 3 times in station #5  

所以預期的輸出類似於上面的 2 個句子。

我不是一個普通的(學習過的).js 程序員,但可以修改系統上運行的主程序中的代碼。

有沒有辦法發出一個站點的溫度重復信號以及多少次?

謝謝。

這是相當的算法,當然它可以更簡單,但我是這樣做的。

創建一個包含時間和溫度的二維數組。 父數組將是times ,子數組將是每個stationtemperatures 每個子數組有 8 個條目。 該子數組中的每個位置都表示station

首先,您必須轉換數據並為每個station創建一組temperatures

[
  [22, 20, 19],
  [26, 26, 28],
  [18, 15, 17],
  ...
]

循環遍歷新集合並計算每個站陣列中有多少重復的temperatures 轉動一個對象中的每個工作站陣列,您可以在其中計數。

[
  {
    "22": 1,
    "20": 1,
    "19": 1,
  },
  {
    "26": 2,
    "28": 1,
  },
  {
    "18": 1,
    "15": 1,
    "17": 1,
  },
  ...
]

現在過濾掉任何低於1每個站的計數,因為您只想要重復項。 並且還將所有內容都放在一個新數組中,該數組也將station編號放入新數組中。

[
  [
    2,
    {
      "26": 2
    }
  ],
  ...
]

從這里您知道站2已記錄溫度26 2次。 您可以通過循環結果將所有這些放在一個字符串中。

運行下面的代碼片段以查看它的運行情況。

 // Make sure that your temp recordings are in a single array with // arrays inside of it. // Each position (left -> right) marking the index of the station. const times = [ [22, 26, 18, 12, 20, 17, 18, 19], [20, 26, 15, 13, 20, 18, 18, 20], [19, 28, 17, 15, 20, 16, 15, 18] ]; const getRepeatedTempsPerStation = times => { // Get longest length of times array. const length = Math.max(...times.map(time => time.length)); // Create a new array with the temps per station. const tempsPerStation = []; for (let i = 0; i < length; i++) { tempsPerStation[i] = []; for (let j = 0; j < times.length; j++) { tempsPerStation[i].push(times[j][i]); } } // Per station count how many times a single temp occurs. const countsPerStation = tempsPerStation.map(temps => temps.reduce((acc, temp) => { acc[temp] = (acc[temp] || 0) + 1; return acc; }, {}) ); // Give each set of counts the number of the station and // filter out all stations without any duplicate numbers. const stationsWithRepeatedTemps = countsPerStation .map((counts, index) => [index + 1, Object.fromEntries( Object.entries(counts).filter(([temp, count]) => count > 1 && !isNaN(temp)) )]) .filter(([station, counts]) => Object.keys(counts).length > 0); return stationsWithRepeatedTemps; } // Get the result. const results = getRepeatedTempsPerStation(times); // Loop over the result and output it in a string. for (const [station, tempCounts] of results) { for (const [temp, count] of Object.entries(tempCounts)) { console.log(`${temp} is repeated ${count} times in station #${station}`); } }

此代碼段還檢查集合數組中是否有任何項目不是數字,因此如果某些數據沒有通過並且null被傳遞,您就很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM