The trick is that the expression needs to determine which layer it’s currently working with. This example uses the layer index, but have to define the first and last index in the expression (you might also be able to calculate it from the layer name):
colors = [[1,0,0,1],[1,.5,0,1],[1,1,0,1],[1,1,1,1]];
firstIndex =1;
lastIndex = 20;
numColors = colors.length;
idx = (index - firstIndex)/(lastIndex-firstIndex);
colorIdx = idx*(numColors-1);
if (colorIdx%1 != 0){
color1 = colors[Math.floor(colorIdx)];
color2 = colors[Math.floor(colorIdx) + 1];
linear(colorIdx%1,0,1,color1,color2);
}else{
colors[colorIdx];
}