Home > Mobile >  check next array element is same or not in javascript?
check next array element is same or not in javascript?

Time:08-18

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

CodePudding user response:

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?

CodePudding user response:

The output you desire will require varied incrementation of i in the loop as you will need to skip the next value when it matches. I suggest using a while loop so that you can conditionally control the incrementation of i. I have changed the logging logic to further illustrate my point:

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

while (i < len) {

  const next = i   1

  if (p[i] == p[next]) {
    console.log(i, p[i], p[next])

    // extra increment when match found
    i  

  } else {
    console.log(i, p[i], 'oops!')
  }

  // always increment by 1
  i  

}

CodePudding user response:

You can skip the second loop. If it is only the very next element you need to compare to the current one, just do p[i 1], check whether it is not outside of the array, then compare the two.

const p = ['12', '13', '13', '14', '15', '15', '16']
var len = p.length;
for (i = 0; i <= len - 1; i  ) {
    var d1 = p[i]
    var d2 = typeof(p[i   1]) !== 'undefined' ? p[i   1] : '';
    if (d1 == d2) {
        i  
        console.log(d1)
        console.log(d2)

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

  • Related