Check if prev id in a loop is not same as current

Advertisements

Lets say there is an array of objects

array = [{ id : 1, name : 'aaa' }, { id : 1, name: 'asd' }, id : 2, name : 'asd' ]

in a loop eg

array.forEach(a =>{ currentId = a.id }

how to check if current id is same or not as prev id

>Solution :

You can use the index to get the previous entry:

array = [{ id : 1, name : 'aaa' }, { id : 1, name: 'asd' }, {id : 2, name : 'asd'} ]

array.forEach((a, index) =>{
  let currentId = a.id

  // Check if previous exists (Index will be 0 on first run)
  if (index) {
    let previousId = array[index - 1].id
    // If exists we can check it
    console.log(currentId === previousId)
  }
})

Leave a ReplyCancel reply