function append (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; } append([0,1], 9, 0) // [0,1,9] append([0,[1]], 9, 0) // [0,[1],9] append([0,[1]], 9, 1) // [0,[1,9]] append([1,[2,[3,[4]]]], 9, 3) // [1,[2,[3,[4,9]]]] append([1,[2,[3],2,[4]]], 9, 2) // [1,[2,[3],2,[4,9]]]
This function works right only if dimension ≤ 3. Also, it is very ugly. What a proper way to do it?
UPDATE:
I know how to recursively get last element of array:
function get_last(array, dimension) { return dimension === 0 ? array[array.length-1] : get_last(array[array.length-1], dimension-1); }
I need append.