You have four arrays with text content that needs to be combined while formatting each substring separately.
The crucial method here is
setTextStyle(startOffset, endOffset, textStyle)
documentation reference
An example from the documentation has been modified and presented below. Although there are methods to link array names and colors, this answer focuses on simplicity to showcase the process. The script can be made more dynamic by users as needed.
function colorSubString() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName("Sheet1")
// declare arrays
var array1 = ["This"]
var array2 = ["child"]
var array3 = ["is carrying"]
var array4 = ["apples"]
// create temporary array to build a complete string
var dataArray = new Array
dataArray = dataArray.concat(array1,array2,array3,array4);
dataArray = dataArray.join(' ');
// save to "BEFORE" cell
sheet.getRange("B1").setValue(dataArray);
// build the foreground color styles
var redFC = SpreadsheetApp.newTextStyle().setForegroundColor("red").build()
var greenFC = SpreadsheetApp.newTextStyle().setForegroundColor("green").build()
var orangeFC = SpreadsheetApp.newTextStyle().setForegroundColor("darkorange").build()
var grayFC = SpreadsheetApp.newTextStyle().setForegroundColor("gray").build()
// apply the styles
var value = SpreadsheetApp.newRichTextValue().setText(dataArray)
.setTextStyle(0, array1[0].length, redFC)
.setTextStyle((array1[0].length+1), (array1[0].length+1+array2[0].length), greenFC)
.setTextStyle(array1[0].length+1+array2[0].length+1, array1[0].length+1+array2[0].length+1+array3[0].length, orangeFC)
.setTextStyle(array1[0].length+1+array2[0].length+1+array3[0].length+1, array1[0].length+1+array2[0].length+1+array3[0].length+1+array4[0].length, grayFC)
// save to the 'AFTER' cell
sheet.getRange("B2").setRichTextValue(value.build());
}
RESULTS
https://i.sstatic.net/rGVqw.jpg