-1

I'm making a sports court booking system and have have an array of booking objects. There are 3 courts that can be booked.

   array = [
      {start: "12:00", end: "13:00", court:1},
      {start: "10:00", end: "11:00", court:1},
      {start: "12:00", end: "13:00", court:2},
      {start: "15:00", end: "16:00", court:3},
      {start: "12:00", end: "13:00", court:3}
  ]

What would be the best way to find the common start and end values that exists for all 3 courts?

The return value I'm looking for would be something like: [{start: '12:00', end: '13:00'}]

This question seems to be getting at a similar problem, but couldn't figure out a way to make it work in my case

avoshmo
  • 55
  • 5

2 Answers2

1

I don't know if this is what you looking for but try this

let array = [
   {start: "12:00", end: "13:00", court:1},
   {start: "10:00", end: "11:00", court:1},
   {start: "12:00", end: "13:00", court:2},
   {start: "15:00", end: "16:00", court:3},
   {start: "12:00", end: "13:00", court:3}
];
let len = array.length;
let res = {};
for(let i =0 ; i< len; i++) {
    let start = array[i]["start"];
    let end = array[i]["end"];
    res[start] = res[start] || {};
    res[start][end] = res[start][end] || 0;
    res[start][end]++;
}
let max = 0;
let result = {};
for(let start in res) {
    for(let end in res[start]) {
        if(res[start][end] > max) {
            max = res[start][end];
            result = {start: start, end: end};
        }
    }
}
console.log(result);
0
const count = []

array.forEach((item) => {
    let countobj = count.find(obj => obj.startend === `${item['start']} ${item['end']}`)
    if (countobj) {
        countobj.court.push(item['court']);
    } else {
        countobj = {
            startend: `${item['start']} ${item['end']}`,
            court: [item['court']],
        }
        count.push(countobj)
    }
})

OUTPUT

[
  { startend: '12:00 13:00', court: [ 1, 2, 3 ] },
  { startend: '10:00 11:00', court: [ 1 ] },
  { startend: '15:00 16:00', court: [ 3 ] }
]
  • I marked the other answer as the solution as it gave the return value I was after, but this solution has made me rethink my whole problem. It is very succinct as well. Thank you – avoshmo Jan 08 '21 at 22:43