skip to Main Content

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

2

Answers


  1. 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)
      }
    })
    Login or Signup to reply.
  2. You can use reduce like:

    const array = [{
      id: 1,
      name: 'aaa'
    }, {
      id: 1,
      name: 'bbb'
    }, {
      id: 2,
      name: 'cccc'
    },
    {
      id:2,
      name:'ddd'
    }];
    
    array.reduce((prev, next) => {
        if (prev.id === next.id) {
          console.log(`${prev.name} has same id of ${next.name}`);
        }
        return next;
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search