function addValue(array, value, dimension) { switch (dimension) { case 0: array.push(value); break; case 1: array[array.length-1].push(value); break; case 2: array[array.length-1][array[array.length-1].length-1].push(value); break; case 3: array[array.length-1][array[array.length-1].length-1][array[array[array.length-1].length-1].length-1].push(value); break; } return array; } addValue([0,1], 9, 0) // [0,1,9] addValue([0,[1]], 9, 0) // [0,[1],9] addValue([0,[1]], 9, 1) // [0,[1,9]] addValue([1,[2,[3,[4]]]], 9, 3) // [1,[2,[3,[4,9]]]] addValue([1,[2,[3],2,[4]]], 9, 2) // [1,[2,[3],2,[4,9]]]
This function is only suitable for dimensions ≤ 3 and can be improved in terms of readability. Is there a better way to achieve the same result?
UPDATE:
I have a recursive get function to retrieve the last element in an array:
function getLast(array, dimension) { return dimension === 0 ? array[array.length-1] : getLast(array[array.length-1], dimension-1); }
However, what I need now is an addValue function.