Like we said earlier, “to a hammer, everything is a nail.” Examine the intent of the array method, forEach()
… to facilitate running a function on every element in the array. One operative word there is, every
. There is no break in a forEach loop. If anything this is not a utility function, but a specialized tool.
What you are asking the method to do is way beneath its qualifications. It is not a straight swap with, for (...) {}
, the more viable tool for the job in this instance. Forgive me if I don’t even discuss your code, which is, frankly, off the mark. In archery they call this a sin but in programming it’s HACF worthy. Fortunately we always get another crack at the problem.
Let’s say we have a list, and we want a reverse representation of that list. We have no other tool but an index, and a length property. What will result will be repetitive, but it will give us some insight.
Reversing a list is essentially pivoting it 180 degrees if we view it as a vector. There is one special condition, odd (length) lists pivot around the actual middle data point which does not move; even lists pivot around a point between the two middle data points.
Given the length, we can find either pivot point.
const list = ['a', 'b', 'c,', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
var pivot = Math.floor(list.length / 2) // an integer
var x1, x2, r;
if (list.length % 2) {
x1 = pivot - 1;
x2 = pivot + 1;
} else {
x1 = pivot - 1;
x2 = pivot;
}
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
x1 = x1 - 1
x2 = x2 + 1
r = list[x1]
list[x1] = list[x2]
list[x2] = r
console.log(list); // ["m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c,", "b", "a"]