Although there may be a more refined way to approach this, I ran out of time to simplify it. The code below accomplishes the desired outcome:
var startingArray = **ARRAY_VALUE_HERE**;
var splitResultStrings = [];
// iterate through each element in the array
for (var i = 0, length = startingArray.length; i < length; i++) {
// split the values for the current array element
var splitVal = startingArray[i].split("|");
var stringNotFound = true;
// loop through the "result strings" array
for (var j = 0, sLength = splitResultStrings.length; j < sLength; j++) {
// if the first letter from the array element matches the first letter of the current "result string" . . .
if (splitResultStrings[j].charAt(0) === splitVal[0]) {
// append the second letter of the array value to the current result string
splitResultStrings[j] = splitResultStrings[j] + splitVal[1];
// indicate that a match has been found and exit the "result string" loop
stringNotFound = false;
break;
}
}
// if there are no result strings that start with the first letter of the array value . . .
if (stringNotFound) {
// concatenate the two values in the current array value and add them as a new "result string"
splitResultStrings.push(splitVal[0] + splitVal[1]);
}
}
Using these arrays, the results are:
startingArray = ["a|c", "a|e", "x|z"] //results in:
splitResultStrings = ["ace", "xz"]
startingArray = ["a|b", "a|c", "a|d", "a|e", "x|y", "x|z"] //results in:
splitResultStrings = ["abcde", "xyz"]
startingArray = ["a|b", "d|e", "d|f", "x|y", "g|h", "g|i", "m|n", "g|j", "a|c", "x|z"] //results in:
splitResultStrings = ["abc", "def", "xyz", "ghij", "mn"]
While there could be more elegant solutions (such as using Map
for easier iteration through "result strings"), this code presents clear steps to guide you towards a final solution.