1

I would like to calculate the time period between two appointments.

They are in this format:

const events = [
{
   start: eventStart,
   end: eventEnd
},
{
   start: eventStart,
   end: eventEnd
},
// more Events
]

Then I tried mapping over this array, referencing the next element to define the end of the "empty" period.

const empty = events.map((element, index, array) => {
   const obj = {
      start: element.end,
      end: array[index + 1].start
   }
   return obj
})

this works mostly fine, however the last element will throw an error since it can't reference the next element.

TypeError: Cannot read property 'start' of undefined

How would you solve that problem? Any help is appreciated!

2
  • you can use if condition to check the index === array.length-1 Commented Jul 19, 2020 at 20:29
  • How many elements do you expect the empty result to have? If the same number as events, then what should the value of end become for the last element? Commented Jul 19, 2020 at 20:35

3 Answers 3

1

Since the last element is a "special case", or "edge case", I would update the code to reflect this. The most straightforward way is to add an if that checks for that special case. In your case, the special case is the last element:

const events = [{
    start: "a",
    end: "b"
  },
  {
    start: "c",
    end: "d"
  },
  {
    start: "e",
    end: "f"
  }
];

const empty = events.map((element, index, array) => {
  let obj;

  if ((events.length - 1) === index) {
    // Last element, do something special?
    obj = {
      start: element.end,
      end: undefined,
      lastElement: true
    }
  } else {
    obj = {
      start: element.end,
      end: array[index + 1].start
    }
  }
  return obj
});

console.log(empty)

Sign up to request clarification or add additional context in comments.

Comments

1

you can put if condition inside map , to for last index

const empty = events.map((element, index, array){

let obj;
if(index === array.length-1){
  obj = {
      start: element.end,
   }
} else {
   obj = {
      start: element.end,
      end: array[index + 1].start
   }
}
   return obj
})

Comments

1

The length of returned array is one element less than the length of original array. You can do it using for loop.

const empty = [];
for(let i = 0; i < events.length - 1; i++){
   const obj = {
      start: events[i].end,
      end: events[i + 1].start
   }
   empty.push(obj) 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.