Задать вопрос
wolf47
@wolf47
Айтишник, немного програмирую на JS

Как высчитать разницу в возрасте за прошедший период?

У меня есть такой массив объектов:
[
    {
        "vid": 133,
        "bdate": "2019-03-31T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 134,
        "bdate": "2019-04-25T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 135,
        "bdate": "2019-03-12T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 136,
        "bdate": "2019-03-14T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 137,
        "bdate": "2019-03-31T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 138,
        "bdate": "2019-02-28T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 150,
        "bdate": "2019-03-18T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 151,
        "bdate": "2019-08-11T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 152,
        "bdate": "2019-05-07T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 153,
        "bdate": "2019-05-24T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 154,
        "bdate": "2019-05-05T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 155,
        "bdate": "2019-08-14T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 156,
        "bdate": "2019-05-07T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 157,
        "bdate": "2019-06-26T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 159,
        "bdate": "2019-10-23T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 170,
        "bdate": "2020-02-05T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 171,
        "bdate": "2020-02-11T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 172,
        "bdate": "2020-02-15T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 173,
        "bdate": "2017-11-11T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 174,
        "bdate": "2019-06-11T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 175,
        "bdate": "2019-09-19T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 176,
        "bdate": "2019-05-14T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 178,
        "bdate": "2019-02-09T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 181,
        "bdate": "2020-02-29T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 184,
        "bdate": "2020-02-23T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 186,
        "bdate": "2020-02-14T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 188,
        "bdate": "2020-03-14T15:00:00-04:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 204,
        "bdate": "2020-02-29T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 112459,
        "bdate": "2018-02-28T14:00:00-05:00",
        "gender": "Ұрғашы"
    },
    {
        "vid": 202,
        "bdate": "2020-02-10T14:00:00-05:00",
        "gender": "Ұрғашы"
    }
]


Это список коров :)
Мне нужно высчитать количество коров за прошедшие годы у которых возраст меньше или равно 20 месяцев.

Вот мой не рабочий код:
function cattlecoefficient() {
  var cows = getCows().filter(function(cow){ 
// из списка забрать только девочек
return cow.gender == "Ұрғашы"; 
});

// массик прошедших лет
  var lastYear = cows.map(function(item){
      return +("" || item.bdate).split("-")[0];
    }).filter(function(y,i,a){
      return a.indexOf(y) === i}
      );

// Возращает [2018, 2019, 2020, 2021]
 Logger.log(lastYear);

  var cowsCount = lastYear.map(function(year){ // перебериаю массив с годами
    return cows.filter(function(cow){
      year = moment("01.01."+year, "DD.MM.YYYY"); // подставляю год
      var age = moment(cow.bdate).diff(year, "month");
        return age >= 20;
      });
  });

  Logger.log(JSON.stringify(cowsCount, null, 4));
 
}


Таким образом, я хочу получить такой результат
[{year: 2018, motherCows: 74}, {year: 2019, motherCows: 77}, {year: 2020, motherCows: 80}]
  • Вопрос задан
  • 110 просмотров
Подписаться 1 Простой Комментировать
Решения вопроса 1
2011mckinsey
@2011mckinsey
Web Developer
Можно попробовать так:
const getYear = (value) => {
  const timeStmp = Date.parse(value);
  return new Date(timeStmp).getUTCFullYear();
}

const monthDiff = (dateFrom) => {
  const baseYear = new Date(dateFrom).getUTCFullYear();
  const baseDate = new Date(baseYear, 11);
  const bday = new Date(dateFrom);
  return new Date(baseDate).getMonth() - bday.getMonth() + 
    (12 * (new Date(baseDate).getFullYear() - bday.getFullYear()));
}


const cowsFemale = cows
  .filter(res => res.gender === 'Ұрғашы')
  .reduce((accum, curVal) => {
  const currentYearBorn = getYear(curVal.bdate);
  const monthsAgo = monthDiff(curVal.bdate);
  const younger = monthsAgo <= 20;

  if (younger) {
    if (!accum[currentYearBorn]) {
      accum[currentYearBorn] = {
        count: 1
      } 
    } else {
      accum[currentYearBorn] = {
        count: accum[currentYearBorn].count + 1
      } 
    }
  }
  return accum
}, {})


Результат будет выглядеть так:
{
 2019: {count: 11}
 2020: {count: 9}
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Fallenyasha
Вы внутри фильтра раз за разом переропределяете year = moment("01.01."+year, "DD.MM.YYYY");
Вынесите его за пределы фильтра

И вместо return cows.filter(function(cow){...}
напишите return { "year": year.getFullYear(), "motherCows": cows.filter(function(cow){...}.length };
Ответ написан
Ваш ответ на вопрос

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

Похожие вопросы
22 дек. 2024, в 20:40
10000 руб./за проект
22 дек. 2024, в 20:34
3000 руб./за проект
22 дек. 2024, в 20:12
10000 руб./за проект