0

How can I get the next item in an array when iterating?

for (let item of list) {
  // item @ index + 1
}

I know I could use the loop with this syntax but prefer the previous one.

for (i = 0; i < list.length; i++) {}
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
doe
  • 395
  • 5
  • 13

4 Answers4

1

The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES6 with calling the entries() method on the array:

for (const [i, v] of ['a', 'b', 'c'].entries()) {
  console.log(i, v)
}
Mir Nawaz
  • 274
  • 1
  • 8
0

Here is the best example you can refer

let list = [4, 5, 6];

for (let i in list) {
    console.log(i); // "0", "1", "2",
}

for (let i of list) {
    console.log(i); // "4", "5", "6"
}
Maheshvirus
  • 4,853
  • 1
  • 31
  • 34
0

Use in to get the index:

for (let index in list) {
  // Use index
}

Or use forEach:

list.forEach((item, index) => {...});
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
0

A simple solution would be to iterate the keys of the list via for(..in..) and, per-iteration, add one to the current index to obtain the index of the next value from the current iteration like so:

let list = [4, 5, 6];

for (let i in list) {

  const next = list[Number.parseInt(i) + 1];

  console.log('curr=', list[i]);
  console.log('next=', next);
  console.log('---');
}

Some points to consider with this are:

  • the last next value will be undefined
  • this approach only works for arrays where values are accessed via integer indices
  • the index of i needs to be parsed to an interger to ensure that the "add one" step returns the index of the next value (rather than a string concatenation)
Dacre Denny
  • 28,232
  • 5
  • 37
  • 57