javascript - 使用 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
所以预期的输出与上面两句话类似。
我不是一个普通的(学过的).js 程序员,但可以调整系统上运行的主程序中的代码。
有没有办法发出一个站的温度重复信号以及重复多少次?
谢谢。
解决方案
这是相当的算法,当然它可以更简单,但我是这样做的。
创建一个包含时间和温度的二维数组。父数组将是times
,子数组将是temperatures
per station
。每个子数组有 8 个条目。该子数组中的每个位置都表示station
.
首先,您必须转换数据并创建temperatures
每个station
.
[
[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
传递,那么你很好。
推荐阅读
- mongodb - mongodb 启动时自动关闭
- python - 如何使用箱线图检测和删除数据集中的异常值?
- bigcommerce - 使用隐身登录时 Facebook 页面插件无法正常工作
- c++ - 如何打印具有最低ascii和其他可能性的字符串
- google-fit - 用于计步的 Google Fit APi 授予第一次用户拒绝的权限
- python - 在列表列表中收集列表的第一项
- python - Odoo:如何在 product.category 中搜索 parent_id 及其所有子项
- python - 使用 numpy 和/或 cv2 在深度图中查找最暗区域
- sql - 这种 UNION 重复数据删除方案在 SQL 中如何工作?
- c++ - 使用 SetWindowPos 函数时的 MFC 调试断言