-2

I'm trying compare an value with the next value in the array, but when the loop is finished, the code that is after is not executed.

var json = [{'id':1},{'id':2},{'id':3},{'id':4},{'id':4},{'id':5},{'id':5}];

for(var i = 0; i < json.length; i++){
    if(json[i].id == json[i+1].id){
        console.log("Equal");
    }
}

console.log('Something'); //This code is not executed

I realized that the problem is this part [i+1]. When I remove the number 1, the code is executed normally.

Does anyone know why this happens?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Diego Soares
  • 175
  • 1
  • 7

2 Answers2

1

You need to have your loop condition as i < json.length-1 instead of i < json.length as having i < json.length as a condition will raise error of:

Uncaught TypeError: Cannot read property 'id' of undefined

And terminate the process so you do not get the last console.log()

var json = [{'id':1},{'id':2},{'id':3},{'id':4},{'id':4},{'id':5},{'id':5}];

for(var i = 0; i < json.length-1; i++){
    if(json[i].id == json[i+1].id){
        console.log("Equal");
    }
}

console.log('Something');
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
-2

You can add this condition in your if statement:

var json = [{'id':1},{'id':2},{'id':3},{'id':4},{'id':4},{'id':5},{'id':5}];

for (var i = 0; i < json.length ; i++) {
    if ((i+1) < json.length  && json[i].id == json[i+1].id) {
        console.log("Equal");
    }
}

console.log('Something');
Sara.
  • 1
  • 2