Извлечение самого низкого и самого высокого времени дня из массива - PullRequest
0 голосов
/ 04 октября 2019

У меня есть массив таких объектов, как этот

const timings = [{
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "10:00", to: "17:00" },
        tuesday: { from: "09:00", to: "10:00" },
        thursday: { from: "05:00", to: "13:00" },
        friday: { from: "02:00", to: "13:30" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "13:00", to: "14:20" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:40" },
        thursday: { from: "11:00", to: "16:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
        sunday: {from: "00:00", to: "23:59"}
    },
]

Я хочу, чтобы выходные данные содержали самое низкое и максимальное значения времени дня из массива

например, вывод:

{
    monday: { from: "10:00", to: "17:00" },
    tuesday: { from: "09:00", to: "13:40" },
    thursday: { from: "05:00", to: "16:00" },
    friday: { from: "02:00", to: "13:30" },
    saturday: { from: "11:00", to: "13:00" },
    sunday: {from: "00:00", to: "23:59"}
}

Я придумал действительно длинное решение, но оно действительно длинное и неэффективное.

мое решение

mondayFrom = timings.map(d => (d.monday && d.monday.from))
mondayTo = timings.map(d => (d.monday && d.monday.to))
tuesdayFrom = timings.map(d => (d.tuesday && d.tuesday.to))
// .... rest of the days

это сгенерирует массив, из которого я могу найти минимум и максимум, но я чувствую, что это плохая логика.

Если есть лучшееКстати, пожалуйста, дайте мне знать. Спасибо

Ответы [ 2 ]

3 голосов
/ 04 октября 2019

Использование Reduce делает его довольно простым

const timings = [{
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "10:00", to: "17:00" },
        tuesday: { from: "09:00", to: "10:00" },
        thursday: { from: "05:00", to: "13:00" },
        friday: { from: "02:00", to: "13:30" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "13:00", to: "14:20" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:40" },
        thursday: { from: "11:00", to: "16:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
        sunday: {from: "00:00", to: "23:59"}
    },
]

let result = timings.reduce((a, x) => {
    Object.entries(x).forEach(([dow, obj]) => {
        if(!a[dow]) {
            a[dow] = Object.assign({}, obj);
        } else {
            a[dow].from = a[dow].from < obj.from ? a[dow].from : obj.from;
            a[dow].to = a[dow].to > obj.to ? a[dow].to : obj.to;
        }
    });
    return a;
}, {});

console.log(result);

примечание: a[dow] = Object.assign({}, obj);, поэтому исходный объект не будет видоизменен

2 голосов
/ 04 октября 2019

Вот пример использования .reduce:

const timings = [{
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "10:00", to: "17:00" },
        tuesday: { from: "09:00", to: "10:00" },
        thursday: { from: "05:00", to: "13:00" },
        friday: { from: "02:00", to: "13:30" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "13:00", to: "14:20" },
        tuesday: { from: "11:00", to: "13:00" },
        thursday: { from: "11:00", to: "13:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
    },

    {
        monday: { from: "12:00", to: "13:00" },
        tuesday: { from: "11:00", to: "13:40" },
        thursday: { from: "11:00", to: "16:00" },
        friday: { from: "11:00", to: "13:00" },
        saturday: { from: "11:00", to: "13:00" },
        sunday: {from: "00:00", to: "23:59"}
    },
];

const formatTimings = function(timings) {

  return timings.reduce(function(result, timing) {
    Object.keys(timing).forEach(function(key) {
      result[key] = {
        from: !result[key] 
          ? timing[key].from 
          : [result[key].from, timing[key].from].sort()[0],
        to: !result[key]
          ? timing[key].to
          : [result[key].to, timing[key].to].sort().reverse()[0]
      };
    })
    return result
  }, {})

}

console.log(formatTimings(timings));
...