@eldenhard2

Как сложить все значения массива по полю месяца?

Такая проблема, получаю данные по API, в массиве объектов, у каждого объекта имеется поле day, в котором получаю дату, так же в этом объекте есть Speed, необходимо сложить значения Speed. distance и wagons, по месяцам
смог реализовать только получение данных, и вычленение из ответа всех дат
Так же получилось получить общую сумму скорости для всех вагонов не учитывая даты

if(this.selectSearch == 1){
                api.getKeyFacts()
                .then(response => {
                    let allData = response.data.mileage['Полувагон']
 let c =  allData.reduce((acc, n) => (acc.speed += n.speed, acc.distance += n.distance, acc), { speed: 0, distance: 0 })
                    for(let i in allData){
                        console.log(allData[i])
                        let dataI = new Date(Date.parse(allData[i].day)).getMonth()
                        
                    }
                   
                })
            }


[
{day: "2022-09-03T00:00:00", speed: 4150, distance: 4150, wagons: 1}
{day: "2022-09-06T00:00:00", speed: 1853, distance: 9265, wagons: 5}
{day: "2022-09-07T00:00:00", speed: 1853, distance: 1853, wagons: 1}
{day: "2022-09-08T00:00:00", speed: 2306, distance: 2306, wagons: 1}
{day: "2022-09-10T00:00:00", speed: 3603, distance: 7206, wagons: 2}
{day: "2022-09-14T00:00:00", speed: 4075, distance: 16300, wagons: 4}
{day: "2022-09-25T00:00:00", speed: 2306, distance: 25366, wagons: 11}
{day: "2022-09-26T00:00:00", speed: 2306, distance: 2306, wagons: 1} 
{day: "2022-10-03T00:00:00", speed: 2418, distance: 2418, wagons: 1}
{day: "2022-10-05T00:00:00", speed: 3004.3333333333335, distance: 9013, wagons: 3}
{day: "2022-10-09T00:00:00", speed: 4522.5, distance: 9045, wagons: 2}
{day: "2022-10-10T00:00:00", speed: 3534.3333333333335, distance: 10603, wagons: 3}
{day: "2022-10-11T00:00:00", speed: 589, distance: 589, wagons: 1}
{day: "2022-10-12T00:00:00", speed: 44, distance: 44, wagons: 1}
{day: "2022-10-14T00:00:00", speed: 4099.25, distance: 16397, wagons: 4}
{day: "2022-10-15T00:00:00", speed: 3173, distance: 12692, wagons: 4}
{day: "2022-10-16T00:00:00", speed: 1720.8461538461538, distance: 22371, wagons: 13}
{day: "2022-10-17T00:00:00", speed: 1249.6666666666667, distance: 3749, wagons: 3}
{day: "2022-10-18T00:00:00", speed: 4130.75, distance: 16523, wagons: 4}
{day: "2022-10-19T00:00:00", speed: 3835.6, distance: 38356, wagons: 10}
{day: "2022-10-20T00:00:00", speed: 2225, distance: 40050, wagons: 18}
{day: "2022-10-21T00:00:00", speed: 3236.5, distance: 12946, wagons: 4}
{day: "2022-10-22T00:00:00", speed: 3066.837837837838, distance: 113473, wagons: 37}
{day: "2022-10-23T00:00:00", speed: 3320, distance: 79680, wagons: 24}
{day: "2022-10-24T00:00:00", speed: 3592.846153846154, distance: 93414, wagons: 26}
{day: "2022-10-25T00:00:00", speed: 3655.52, distance: 91388, wagons: 25}
{day: "2022-10-26T00:00:00", speed: 2749.457142857143, distance: 96231, wagons: 35}
{day: "2022-10-27T00:00:00", speed: 4049.15, distance: 80983, wagons: 20}
{day: "2022-10-28T00:00:00", speed: 2163.8518518518517, distance: 58424, wagons: 27}
{day: "2022-10-29T00:00:00", speed: 1652.6666666666667, distance: 59496, wagons: 36}
{day: "2022-10-30T00:00:00", speed: 2264, distance: 199232, wagons: 88}
{day: "2022-10-31T00:00:00", speed: 1371.4736842105262, distance: 52116, wagons: 38}
{day: "2022-11-01T00:00:00", speed: 2135.9814814814813, distance: 115343, wagons: 54}
{day: "2022-11-02T00:00:00", speed: 1653.32, distance: 82666, wagons: 50}
{day: "2022-11-03T00:00:00", speed: 1086.4634146341464, distance: 44545, wagons: 41}
{day: "2022-11-04T00:00:00", speed: 1521.8709677419354, distance: 47178, wagons: 31}
]
  • Вопрос задан
  • 99 просмотров
Решения вопроса 2
sergiks
@sergiks Куратор тега JavaScript
♬♬
Стоит включить и год, и месяц в хэш, а то мало ли, более 1 года попадёт в выборку.
const props = ['speed', 'distance', 'wagons'];

const result = data.reduce((acc, c) => {
  const yearMonth = c.day.substring(0, 7); // '2022-03'
  props.forEach(prop => {
    acc[prop][yearMonth] = (acc[prop][yearMonth] ?? 0) + c[prop];
  });
  return acc;
}, Object.fromEntries(props.map(prop => [prop, {}])));
Результат
{
  "speed": {
    "2022-09": 22452,
    "2022-10": 65668.58282444967,
    "2022-11": 6397.635863857564
  },
  "distance": {
    "2022-09": 68752,
    "2022-10": 1119233,
    "2022-11": 289732
  },
  "wagons": {
    "2022-09": 26,
    "2022-10": 427,
    "2022-11": 176
  }
}


Другой вариант:
const hashMap = data.reduce((acc, { day, ...rest }) => {
  const hash = day.substring(0, 7);
  if (Object.hasOwn(acc, hash)) {
    Object.keys(rest).forEach(prop => acc[hash][prop] += rest[prop]);
  } else {
    acc[hash] = { day: hash, ...rest };
  }

  return acc;
}, {});

const result = Object.values(hashMap);
Результат
[
  {
    "day": "2022-09",
    "speed": 22452,
    "distance": 68752,
    "wagons": 26
  },
  {
    "day": "2022-10",
    "speed": 65668.58282444967,
    "distance": 1119233,
    "wagons": 427
  },
  {
    "day": "2022-11",
    "speed": 6397.635863857564,
    "distance": 289732,
    "wagons": 176
  }
]
Ответ написан
XanXanXan
@XanXanXan
const monthData = allData.reduce((acc, { day, speed, distance, wagons }) => {
  const yearMonth = day.match(/\d{4}-\d{2}(?=-\d{2})/)[0];
    
  if (acc[yearMonth]) {
    acc[yearMonth].speed += speed;
    acc[yearMonth].distance += distance;
    acc[yearMonth].wagons += wagons;
  } else {    
    acc[yearMonth] = { speed, distance, wagons };
  }

  return acc;
}, {})
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
21 нояб. 2024, в 22:21
3000 руб./в час
21 нояб. 2024, в 21:42
100000 руб./за проект
21 нояб. 2024, в 21:30
500 руб./за проект