2

How can a for of loop in es6 be made to start on the last item in the array and go down to the first instead of how it normally uses the variable++ behavior to iterate from first to last in the array's index.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875

2 Answers2

4

The for..of loop is one-directional, proceeding through the iterator's natural order. You can't change the direction of the iterator.

You could, of course, use a simple for loop instead:

for (let i = theArray.length - 1; i >= 0; --i) {
    let entry = theArray[i];
    // ...
}

...but to use an interator for this (e.g., with for..of), you have to change what it's iterating over, or the iterator it's using.

One way to do that is to reverse the order of the array first. Unfortunately, Array#reverse modifies the array in place, and so if you want to keep the array in its original order, you have to clone it first (live example on Babel's REPL):

for (let entry of theArray.slice().reverse()) {
    // ...
}

Another way is to write a reusable generator function that loops backward through an array:

function *backward(a) {
  for (let i = a.length - 1; i >= 0; --i) {
    yield a[i];
  }
}

then:

let theArray = ["one", "two", "three"];
for (let entry of backward(theArray)) {
  console.log(entry);
}

Live example on Babel's REPL

As RGraham points out, now that we can subclass arrays, you could even create an array subclass that provides backward as its default iterator.

Gosh, so many options. :-)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-2
const array = [1,2,3,4,5];
for (let i = array.length; i--;) {
    console.log(array[i]);
}

//5
//4
//3
//2
//1

Babel Repl