Skip to content

Instantly share code, notes, and snippets.

@Daniel-Hug
Created June 26, 2017 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Hug/6ec686498f3cecf5009fbaf663dea50c to your computer and use it in GitHub Desktop.
Save Daniel-Hug/6ec686498f3cecf5009fbaf663dea50c to your computer and use it in GitHub Desktop.
JS function: create 2d array or multidimensional matrix w/o constructor
// create 2d array or multidimensional matrix
function createMatrix() {
var matrix = [];
matrix.add = function(val, i1, i2/*, ...*/) {
var cur = matrix, curI;
// loop from 2nd argument to 2nd to last
for (var i = 1; i < arguments.length - 1; i++) {
curI = arguments[i];
// add an empty array in the current array of the matrix at every index
// before and including the current index until a defined value is reached
for (var j = curI; j >= 0 && !(curI in cur); j--) {
cur[j] = [];
}
cur = cur[curI];
}
curI = arguments[i];
cur[curI] = val;
// add an empty array in the current array of the matrix at every
// index before the added value until another defined value is reached
for (var k = curI - 1; k >= 0 && !(curI in cur); k--) {
cur[k] = [];
}
};
return matrix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment