Skip to content

Instantly share code, notes, and snippets.

@gnclmorais gnclmorais/flatter.js
Last active Aug 29, 2017

Embed
What would you like to do?
Iterate over a matrix in JavaScript, cell by cell
function* flatten(matrix) {
for (var i = 0; i < matrix.length; i += 1) {
let column = matrix[i];
if (!Array.isArray(column)) yield column;
for (var j = 0; j < column.length; j += 1) {
yield column[j];
}
}
}
const matrix = [
[1, 2],
[3, 4]
];
const walker = flatten(matrix);
console.log(walker.next().value); // 1
console.log(walker.next().value); // 2
console.log(walker.next().value); // 3
console.log(walker.next().value); // 4
console.log(walker.next().value); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.