Skip to content

Instantly share code, notes, and snippets.

@adambene
Created March 6, 2018 14:58
Show Gist options
  • Select an option

  • Save adambene/bc5de9acaf60d4521ac32e7564d6c208 to your computer and use it in GitHub Desktop.

Select an option

Save adambene/bc5de9acaf60d4521ac32e7564d6c208 to your computer and use it in GitHub Desktop.
Iterate through an array in an alternating fashion in JavaScript
class AlternatingArray extends Array {
constructor(...args) {
super(...args);
}
*[Symbol.iterator](){
for (let i = 0; i < this.length; i += 2) {
yield this[i];
}
for (let i = 1; i < this.length; i += 2) {
yield this[i];
}
}
}
const a = new AlternatingArray(1, 2, 3, 4, 5, 6, 7, 8);
console.log([...a]); // [1, 3, 5, 7, 2, 4, 6, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment