js里面如何让数组的元素进行前后比较?

这是一个聊天记录的数组,用时间升序和标识字段进行了排序,例如r=[name,num]为
{x,1} , {x,1} , {x,1} ,{x,2} ,{x,2} , {x,2} ,{x,2},其中x是随便的

我自己写的代码是

for ( let i =  0 ; i < r.length ; i++){
   if ( r[i].num != r[i+1].num ){
         this.data.a.push(r[i])
     }
}

但发现这样写的话**Cannot read property '_num_' of undefined**
用了嵌套循环也还是不行,请问这是为什么啊

r[i+1].num这个在条件最后一定后出现越界。条件要改为 i < r.length-1