Сравнение объектов внутри одного и того же массива JavaScript

#javascript #arrays #csv

#javascript #массивы #csv

Вопрос:

Я пытаюсь сравнить объекты внутри одного и того же массива. У меня есть CSV-файл, который содержит некоторые данные в виде списка с разделителями. После загрузки файла мне нужно отфильтровать его и распечатать вывод на экран или консоль на основе двух условий:

Если для одного и того же satelliteID есть три показания, которые находятся ниже красного нижнего предела в течение пятиминутного интервала.

Если для одного и того же спутника три показания термостата превышают красный верхний предел в течение пятиминутного интервала.

Я полагаю, что могу использовать array.filter, а затем array.map для достижения желаемого результата, но не уверен, что дальше делать с циклическим перебором массива и сравнением объектов.

Вот желаемый результат:

 [
    {
        "satelliteId": 1000,
        "severity": "RED HIGH",
        "component": "TSTAT",
        "timestamp": "2018-01-01T23:01:38.001Z"
    },
    {
        "satelliteId": 1000,
        "severity": "RED LOW",
        "component": "BATT",
        "timestamp": "2018-01-01T23:01:09.521Z"
    }
]
  

Вот как выглядит CSV-файл:

 timestamp|satelliteid|redhi&h|yellowhi&h|yellowlow|redlow|rawvalue|component
20180101 23:01:05.001|1001|101|98|25|20|99.9|TSTAT
20180101 23:01:09.521|1000|17|15|9|8|7.8|BATT
20180101 23:01:26.011|1001|101|98|25|20|99.8|TSTAT
20180101 23:01:38.001|1000|101|98|25|20|102.9|TSTAT
20180101 23:01:49.021|1000|101|98|25|20|87.9|TSTAT
20180101 23:02:09.014|1001|101|98|25|20|89.3|TSTAT
20180101 23:02:10.021|1001|101|98|25|20|89.4|TSTAT
20180101 23:02:11.302|1000|17|15|9|8|7.7|BATT
20180101 23:03:03.008|1000|101|98|25|20|102.7|TSTAT
20180101 23:03:05.009|1000|101|98|25|20|101.2|TSTAT
20180101 23:04:06.017|1001|101|98|25|20|89.9|TSTAT
20180101 23:04:11.531|1000|17|15|9|8|7.9|BATT
20180101 23:05:05.021|1001|101|98|25|20|89.9|TSTAT
20180101 23:05:07.421|1001|17|15|9|8|7.9|BATT
  

Вот код, который я написал, чтобы принять файл и проанализировать его.

 const readFile = require("fs").readFile;
readFile("./data.csv", "utf-8", (err, data) =&&t; {
  //Store final results
  var result = [];

  //Split Each line in the CVS
  const lines = data.split("n");

  //Assumes the first line in the csv is the header
  var headers = lines[0].split("|");

  //Create value pair
  for (var i = 1; i < lines.len&th; i  ) {
    var obj = {};
    var currentline = lines[i].split("|");

    for (var j = 0; j < headers.len&th; j  ) {
      obj[headers[j]] = currentline[j];
    }

    //Add objects to result array
    result.push(obj);
  }
  console.lo&(result);
});
  

Это то, что регистрируется в консоли на данный момент после синтаксического анализа CSV-файла.

 [
  {
    timestamp: '20180101 23:01:05.001',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '99.9',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:01:09.521',
    satelliteid: '1000',
    redhi&h: '17',
    yellowhi&h: '15',
    yellowlow: '9',
    redlow: '8',
    rawvalue: '7.8',
    component: 'BATT'
  },
  {
    timestamp: '20180101 23:01:26.011',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '99.8',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:01:38.001',
    satelliteid: '1000',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '102.9',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:01:49.021',
    satelliteid: '1000',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '87.9',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:02:09.014',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '89.3',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:02:10.021',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '89.4',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:02:11.302',
    satelliteid: '1000',
    redhi&h: '17',
    yellowhi&h: '15',
    yellowlow: '9',
    redlow: '8',
    rawvalue: '7.7',
    component: 'BATT'
  },
  {
    timestamp: '20180101 23:03:03.008',
    satelliteid: '1000',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '102.7',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:03:05.009',
    satelliteid: '1000',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '101.2',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:04:06.017',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '89.9',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:04:11.531',
    satelliteid: '1000',
    redhi&h: '17',
    yellowhi&h: '15',
    yellowlow: '9',
    redlow: '8',
    rawvalue: '7.9',
    component: 'BATT'
  },
  {
    timestamp: '20180101 23:05:05.021',
    satelliteid: '1001',
    redhi&h: '101',
    yellowhi&h: '98',
    yellowlow: '25',
    redlow: '20',
    rawvalue: '89.9',
    component: 'TSTAT'
  },
  {
    timestamp: '20180101 23:05:07.421',
    satelliteid: '1001',
    redhi&h: '17',
    yellowhi&h: '15',
    yellowlow: '9',
    redlow: '8',
    rawvalue: '7.9',
    component: 'BATT'
  }
]
  

Комментарии:

1. Что это за интервал в 5 минут? и я думаю, что redhi&h или redlow определяется с использованием rawvalue. правильно?

2. Да, вы используете значение rawvalue, чтобы определить, попадает ли оно в hi&h или low, поэтому, если бы я должен был использовать filter, я бы, вероятно, выбрал result.filter(item =&&t; item.rawvalue &&t; item.redlow) или что-то в этом роде. 5-минутный интервал включает в себя сравнение временных меток, чтобы увидеть, находятся ли они в пределах 5 минут друг от друга для одного и того же идентификатора

Ответ №1:

Вы можете reduce вместе с filter .

 const arr = [ { timestamp: '20180101 23:01:05.001', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '99.9', component: 'TSTAT' }, { timestamp: '20180101 23:01:09.521', satelliteid: '1000', redhi&h: '17', yellowhi&h: '15', yellowlow: '9', redlow: '8', rawvalue: '7.8', component: 'BATT' }, { timestamp: '20180101 23:01:26.011', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '99.8', component: 'TSTAT' }, { timestamp: '20180101 23:01:38.001', satelliteid: '1000', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '102.9', component: 'TSTAT' }, { timestamp: '20180101 23:01:49.021', satelliteid: '1000', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '87.9', component: 'TSTAT' }, { timestamp: '20180101 23:02:09.014', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '89.3', component: 'TSTAT' }, { timestamp: '20180101 23:02:10.021', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '89.4', component: 'TSTAT' }, { timestamp: '20180101 23:02:11.302', satelliteid: '1000', redhi&h: '17', yellowhi&h: '15', yellowlow: '9', redlow: '8', rawvalue: '7.7', component: 'BATT' }, { timestamp: '20180101 23:03:03.008', satelliteid: '1000', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '102.7', component: 'TSTAT' }, { timestamp: '20180101 23:03:05.009', satelliteid: '1000', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '101.2', component: 'TSTAT' }, { timestamp: '20180101 23:04:06.017', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '89.9', component: 'TSTAT' }, { timestamp: '20180101 23:04:11.531', satelliteid: '1000', redhi&h: '17', yellowhi&h: '15', yellowlow: '9', redlow: '8', rawvalue: '7.9', component: 'BATT' }, { timestamp: '20180101 23:05:05.021', satelliteid: '1001', redhi&h: '101', yellowhi&h: '98', yellowlow: '25', redlow: '20', rawvalue: '89.9', component: 'TSTAT' }, { timestamp: '20180101 23:05:07.421', satelliteid: '1001', redhi&h: '17', yellowhi&h: '15', yellowlow: '9', redlow: '8', rawvalue: '7.9', component: 'BATT' } ];
const res = arr.reduce((acc, {timestamp,satelliteid:satelliteId,redlow,redhi&h,component})=&&t;{
  const &etDate = str =&&t; new Date(str.slice(0,4) '-' str.slice(4,6) '-' str.slice(6));
  const date = &etDate(timestamp);
  let severity;
  if(arr.filter(obj=&&t; obj.rawvalue <  redlow amp;amp; &etDate(obj.timestamp) - date <= 5 * 60 * 1000).len&th &&t;= 3){
    severity = 'RED LOW';
  } else if(arr.filter(obj=&&t; obj.rawvalue &&t;  redhi&h amp;amp; &etDate(obj.timestamp) - date <= 5 * 60 * 1000).len&th &&t;= 3){
    severity = 'RED HIGH';
  }
  if(severity){
    acc.push({satelliteId,severity,component,timestamp});
  }
  return acc;
}, []);
console.lo&(res);