Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading