Фильтр данных JS и группа неверны

Я работаю с массивом словарей и хочу сгруппировать данные по периоду времени, у меня есть решение, как это сделать.

Но теперь я обнаружил проблемы, за последние часы данные не отображаются в сгруппированном массиве.

Код:

    // Dictionary array:
var array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
// And I have time periods, for ex:
var time = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

var formatedTime = time.map(function(val) {
    return val.split(" - ");
});

var grouped = formatedTime.reduce((groups, currentValue, cI) => {
    let min = parseInt(currentValue[0].substring(0,2));
    let max = parseInt(currentValue[1].substring(0,2));
    let filtered = array.filter(val => {
        let validDate = val.dateTime.replace(///g,'-').replace(' ','T').replace('19','2019');
        let date = new Date(validDate).getHours();
        let result = false;
        if (date >= min && date < max) {
            return true;
        } else {
            return false;
        }
    });
    

    let date = currentValue[0] + " - " + currentValue[1];
    groups.push({
        time: date,
        groupedData: filtered
    });
    return groups;

}, []);

console.info(grouped);

Итак, как вы можете видеть в массиве, у меня есть данные для время 14:00 - 14:45 после фильтрации данных, которые отображаются неправильно.

В моем массиве у меня есть две записи:

{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
{ item: "item", category: "category", dateTime: "19/05/23 14:37:33" },

Я пытаюсь найти решение, но я застрял.

Ожидаемый результат:

{
    "time": "14:00 - 14:45",
    "groupedData": [{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
    { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }]

 }

Каков ожидаемый результат?

Maheer Ali 27.05.2019 09:35

@MaheerAli, у меня есть вопрос

qunz666 27.05.2019 09:38

Вы сравниваете только часы, но должны сравнивать и минуты.

Robby Cornelissen 27.05.2019 09:38

Я думаю, вы задавали этот вопрос несколько дней назад. stackoverflow.com/questions/56269154/…

Murali Nepalli 27.05.2019 09:40

@MuraliNepalli нет

qunz666 27.05.2019 09:40
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
5
57
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Ответ принят как подходящий

Вы можете напрямую сравнить время и найти сначала группу, а затем элемент в наборе результатов.

var array = [{ item: "item", category: "category", dateTime: "19/05/23 05:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 05:21:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:31:33" }, { item: "item", category: "category", dateTime: "19/05/23 06:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:34:33" }, { item: "item", category: "category", dateTime: "19/05/23 07:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 08:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:16:33" }, { item: "item", category: "category", dateTime: "19/05/23 09:46:33" }, { item: "item", category: "category", dateTime: "19/05/23 10:36:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:47:33" }, { item: "item", category: "category", dateTime: "19/05/23 11:55:33" }, { item: "item", category: "category", dateTime: "19/05/23 12:37:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:27:33" }, { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }],
    time = ["05:45 - 06:00", "06:00 - 07:00", "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00", "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00", "13:00 - 14:00", "14:00 - 14:45"],
    result = array.reduce((r, o) => {
        var part = o.dateTime.slice(9, 14),
            group = time.find(t => {
                var [min, max] = t.split(' - ');
                return min <= part && part < max;
            }),
            temp = r.find(({ time }) => time === group);

        if (!group) return r;
        if (!temp) {
            r.push({ time: group, groupedData: [o] });
            return r;
        }
        temp.groupedData.push(o);
        return r;
    }, []);

console.info(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

В вашем коде вы сравниваете только часы и игнорируете минуты. Это вызывает проблему с периодом 14:00 - 14:45.

Из-за того, как даты отформатированы и как вы выполняете сравнение, вы можете просто обойтись здесь сравнением на основе строк:

const array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];

const times = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

const grouped = times.map(time => {
  const [min, max] = time.split(' - ');
  const groupedData = array.filter(({dateTime}) => {
    const ts = dateTime.substring(9, 14);
    
    return ts >= min && ts < max;
  });
  
  return {time, groupedData};
});

console.info(grouped);

    const array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
    // And I have time periods, for ex:
    const times = ["05:45 - 06:00", "06:00 - 07:00",
        "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
        "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
        "13:00 - 14:00", "14:00 - 14:45"
    ];

    const result = [];

    times.forEach((time) => {

        const [min, max] = time.split(" - ");

        const groupedData = array.filter(({ dateTime }) => {
            return `${min}:00`.localeCompare(dateTime.slice(-8)) <= 0 && `${max}:00`.localeCompare(dateTime.slice(-8)) >= 0;
        })

        result.push({
            time,
            groupedData
        });
    });


    console.info('@>result', result)

Другие вопросы по теме