Is there a way in JavaScript to select a element of a multidimential array. Where the depth/rank/dimensionality is variable and the keys are given by a array of indices. Such that i don’t have handle every possible dimentional depth separately. concretely speaking i want do get rid of switch cases like here:
/**
* set tensor value by index
* @type {array} indices [ index1, index2, index3 ] -> length == rank.
* @type {string} value.
*/
tensor.prototype.setValueByIndex = function( indices, value ) {
var rank = indices.length;
switch(rank) {
case 0:
this.values[0] = value;
break;
case 1:
this.values[indices[0]] = value;
break;
case 2:
this.values[indices[0]][indices[1]] = value;
break;
case 3:
this.values[indices[0]][indices[1]][indices[2]] = value;
break;
}
}
Where this.values is a multidimensional array.
such that i get something that looks more like this:
/**
* set tensor value by index
* @type {array} indices, [ index1, index2, index3 ] -> length == rank
* @type {string} value
*/
tensor.prototype.setValueByIndex = function( indices, value ) {
var rank = indices.length;
this.values[ indices ] = value;
}
Thank you in advance!
This uses
arrayto point to the nested array we are currently at and reads through theindiciesfor find the nextarrayvalue from the currentarray. Once we reach the last index in theindiceslist, we have found the array where we want to deposit the value. The final index is the slot in that final array where we deposit the value.