Here's my code -
var a = 'abcde'.split(''); var b = 'cxefgh'.split(''); //abfgh a.forEach((e, index) => { console.log(e, index) if (b.indexOf(e) > -1) { b.splice(b.indexOf(e), 1); a.splice(index, 1); } }) //Here the output - //a 0 //b 1 //c 2 //e 3
Why this loop isn't printing d. What's the silliest thing that I am missing here?
You are changing a
while iterating on it, resulting in discrepancy.
You should consider working on clone of a
(created with a.slice()
) and then changing the a
and b
, if matches are found.
var a = 'abcde'.split(''); var b = 'cxefgh'.split(''); //abfgh a.slice().forEach((e , index)=> { console.log(e, index) if(b.indexOf(e) > -1) { b.splice(b.indexOf(e) , 1); // Find where it is in `b` and remove it. a.splice(a.indexOf(e) , 1); // Find where it is in `a` and remove it. } }) console.log(a); // ['a', 'b', 'd'] console.log(b); // ['x', 'f', 'g', 'h']
a.splice(index , 1);
is executed when e
is 'c'
. index
is 2 at that point, so a
becomes ['a', 'b', 'd', 'e']
(the splice removes the 'c'
). Then the forEach
moves on with index
3, which is (now) 'e'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.