October 21, 2017

For in is not good for array looping with index

I am having a different result from two simple looping approach.

for (let i = 0; i < left.length; i++) {
	bfs([...temp, left[i]], [...left.slice(0, i), ...left.slice(i + 1)]);
}

and

for (let i in left) {
	bfs([...temp, left[i]], [...left.slice(0, i), ...left.slice(i + 1)]);
}

The problem came from a bad use of for in for array looping with the care of indexing

Note:for...inshould not be used to iterate over anArraywhere the index order is important. --- MDN