George Edwards
George Edwards

Reputation: 9229

Identifying the next item in current for of loop iteration Typescript

In my TypeScript project, I want to compare the values in an Array with the next value. If I am doing this in JavaScript I would do something like this:

//JS
for (var i = 0; i < codeBlocks.length; i++) {
    var j = i + 1;
    if (codeBlocks[i] > codeBlocks[j]) {return true;}
    return false;
}

However, I really like the Typescript for of syntax as it is much more readable.

//TS
for (let codeBlock of codeBlocks) {
    //logic
}

Is there a way of describing the "next iteration" value in the typescript for...of loop?

Upvotes: 4

Views: 5243

Answers (6)

user663031
user663031

Reputation:

Here is a generator which generates pairs of elements:

function *pairs(array) {
  let prev = array.shift();

  for (v of array) {
    yield [prev, v];
    prev = v;
  }
}

for (let pair of pairs([1,2,3])) { console.log(pair); }

If you want to also generate a last pair with the last value and undefined, then just add a yield [prev, undefined]; at the end of the function.

Upvotes: 0

Manwal
Manwal

Reputation: 23836

You can use entries()

for (var [index, codeBlock] of codeBlocks.entries()) 
{ 
  // your code you can use index 
}

DEMO

Example snippet:

var test = ['a','b','c']
for (var [index, cur] of test.entries()) 
{ 
  var j = index + 1;
  console.log("Current value: "+cur+"  Next value: "+test[j])
}

Upvotes: 6

Jofy Baby
Jofy Baby

Reputation: 122

If you want the index of an element , use the foreach function:

codeBlocks.forEach((item, index) => {
    console.log(item); // item in the array
    console.log(index); // item index in the array
});

Upvotes: 1

V.pique
V.pique

Reputation: 71

first Your javascript code is wrong, the last element will compare with undefined

maybe you should give a look to reduce function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 0

toskv
toskv

Reputation: 31612

No. That's not the purpose of for .. of. You can read more about it on MDN.

You must use the for (var i = 0; i < codeBlocks.length; i++) syntax for that.

Upvotes: 0

Maxx
Maxx

Reputation: 1748

You can use same syntax for (var i = 0; i < codeBlocks.length; i++) in TypeScript. But your cycle will run only once.

Upvotes: 0

Related Questions