TopDocDev
TopDocDev

Reputation: 15

Reference next element in map function

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!

Upvotes: 1

Views: 701

Answers (3)

nibble
nibble

Reputation: 404

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) 
}

Upvotes: 1

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

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
})

Upvotes: 1

skovy
skovy

Reputation: 5650

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)

Upvotes: 1

Related Questions