JSFiddle - React, Tailwind, and code Playground

JavaScript

var myarrayx =  [1,1,3]; //5

function morphArray(myarray, index, target){
    
    //get limit
	var limit = 0;
    for(var i = 0; i < myarray.length; i++){
        limit += myarray[i];
    }
	
    //accumulate value on the array to gain target value
    var accu = 0;
    for(var i = 0; i < myarray.length; i++){
		var thisIndex = myarray[i];
        for(var j = 0; j < thisIndex; j++){
			console.log(accu);
			if(accu != target){
				myarray[i]--;  
				accu++;
			}
			else{
				break;
			}
        }
    }
    
	//remove the zeroes on the array
	for(var k = 0; k < myarray.length; k++){
		if(myarray[k] == 0){
			myarray.splice(k, 1);
		}
	}
	
	//check if the target index is still available
	if((myarray.length - 1) > index){
		//index is not available anymore.. just push it
		myarray.push(target);
	}
	else{
		//insert the element in the desired index
		myarray.splice(index, 0, target);
	}
	
 
	return myarray;
}

console.log('----'+morphArray(myarrayx, 0, 2));