I want to check that next Element in my array is same
JavaScript
x
29
29
1
const p = ['12', '13', '13', '14', '15', '15', '16']
2
3
var len = p.length
4
5
6
7
for (i = 0; i <= len - 1; i++) {
8
9
10
var d1 = p[i]
11
// document.write(d1)
12
13
14
for (j = i + 1; j <= i + 1; j++) {
15
var d2 = p[j]
16
// document.write(d2)
17
if (d1 == d2) {
18
19
console.log(d1)
20
console.log(d2)
21
22
} else {
23
console.log(d1)
24
console.log('oops!')
25
}
26
break;
27
}
28
29
}
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:
JavaScript
1
10
10
1
const p = ['12', '13', '13', '14', '15', '15', '16']
2
let len = p.length;
3
4
for (let i = 0; i < len; i++) {
5
console.log(p[i]);
6
if (i+1 >= len || p[i] != p[i+1])
7
console.log('oops!'); // print oops only if we're at the end of the array OR elements are different
8
else
9
console.log(p[i++]); // this will run only if we're before the end of array AND numbers are the same
10
}
note: what about multiple (more than 2) consecutive equal numbers?