You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中用forEach处理数组:去重传感器并保留最新时间数据

Fix Duplicate Sensors by Keeping Latest Temperature Data

Got it, let's resolve that duplicate sensor display issue! The core problem right now is that we're creating a gauge for every single entry in the API response—even if they belong to the same sensor. We need to first filter the data to retain only the most recent entry for each sensor, then generate our ECharts configurations from that cleaned dataset.

Step 1: Clean the Sensor Data (Keep Latest Entries)

We'll use Array.reduce() to group our data by sensor name, and for each group, we'll only keep the entry with the newest dateandtime value. Here's the modified code with this logic:

this.gaugeOption = [];
this.global.getData(`/services/getData.php`)
  .pipe(take(1))
  .subscribe((res: any) => {
    // First: Process raw data to keep only the latest entry per sensor
    const latestSensorData = Object.values(res.reduce((accumulator, currentEntry) => {
      // Convert date string to timestamp for easy comparison
      const currentTimestamp = new Date(currentEntry.dateandtime).getTime();
      
      // If sensor isn't in accumulator, or current entry is newer than stored one
      if (!accumulator[currentEntry.sensor] || 
          new Date(accumulator[currentEntry.sensor].dateandtime).getTime() < currentTimestamp) {
        accumulator[currentEntry.sensor] = currentEntry;
      }
      return accumulator;
    }, {}));

    this.rowData = latestSensorData;
    console.log('Cleaned data (latest per sensor):', this.rowData);

    // Then: Generate gauge options from the cleaned dataset
    this.rowData.forEach(room => {
      this.gaugeOption.push({
        title: {
          text: room.sensor,
          left: '5%',
          top: '5%',
          textStyle: {
            fontSize: 18,
          }
        },
        tooltip: {
          formatter: "{a} <br/>{b} : {c}°"
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: false },
            restore: { show: false },
            saveAsImage: { show: false }
          }
        },
        series: [
          {
            name: 'Temperature',
            type: 'gauge',
            center: ['40%', '70%'],
            splitNumber: 10,
            radius: '70%',
            axisLine: {
              lineStyle: {
                color: [[0.2, '#48b'], [0.8, '#228b22'], [1, '#ff0000']],
                width: 8
              }
            },
            axisTick: {
              splitNumber: 10,
              length: 12,
              lineStyle: { color: 'auto' }
            },
            axisLabel: {
              textStyle: { color: 'auto' }
            },
            splitLine: {
              show: true,
              length: 30,
              lineStyle: { color: 'auto' }
            },
            pointer: { width: 5 },
            title: {
              show: true,
              offsetCenter: [0, '65%'],
              textStyle: { fontWeight: 'bolder' }
            },
            detail: {
              formatter: '{value}°',
              textStyle: { color: 'auto', fontWeight: 'bolder' }
            },
            data: [{ value: room.temperature, name: "Temperature" }]
          }
        ]
      });
    });
  });

How This Works:

  • Data Cleaning: The reduce function builds an object where each key is a sensor name, and the value is the most recent entry for that sensor. We convert dateandtime strings to timestamps to easily compare which entry is newer.
  • Gauge Generation: We now loop over the cleaned array (each sensor has exactly one entry) to create ECharts configurations—no more duplicate gauges for the same sensor!

Your list.component.html doesn't need any changes, since it already loops over gaugeOption which now contains unique sensor entries only.

内容的提问来源于stack exchange,提问作者ABC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:40:37