Skip to content
Advertisement

check next array element is same or not in javascript?

I want to check that next Element in my array is same

const p = ['12', '13', '13', '14', '15', '15', '16']

var len = p.length



for (i = 0; i <= len - 1; i++) {


    var d1 = p[i]
        // document.write(d1)


    for (j = i + 1; j <= i + 1; j++) {
        var d2 = p[j]
            // document.write(d2)
        if (d1 == d2) {

            console.log(d1)
            console.log(d2)

        } else {
            console.log(d1)
            console.log('oops!')
        }
        break;
    }

}

Here I have 7 Elements in my array in which same element is same as their before element but some are not.

What I want : If the next Element of my Element is not the same with the first one so automatically it print opps in place of next and then check for next. as I write in my code but my code is correct

Output I want = 12 oops 13 13 14 oops 15 15 16 oops

Output I’m geeting= 12 oops! 13 13 13 oops! 14 oops! 15 15 15 oops! 16 oops!

Anyone help me with this? I don’t know what to do.

Thank You

Advertisement

Answer

I’m not very sure that I understand logic and how to handle all edge cases, but here is variant which fits provided expected output:

const p = ['12', '13', '13', '14', '15', '15', '16']
let len = p.length;

for (let i = 0; i < len; i++) {
    console.log(p[i]);
    if (i+1 >= len || p[i] != p[i+1])
        console.log('oops!'); // print oops only if we're at the end of the array OR elements are different
    else
      console.log(p[i++]); // this will run only if we're before the end of array AND numbers are the same
}

note: what about multiple (more than 2) consecutive equal numbers?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement