JavaScript crea una matriz anidada a partir de valores de cadena

De mi fuente de datos obtengo valores como;

USA        |Arizona
USA        |Florida
UK         |England |Northamptonshire
UK         |England |Derbyshire
UK         |Wales   |Powys
Switzerland|Lucern

Estos son valores de texto plano que se repiten en una columna.

Necesito construirlos dinámicamente en una matriz anidada

source: [
    {title: "USA",  children: [
      {title: "Arizona"},
      {title: "Florida"}
    ]}
  ],

Segúnhttps: //github.com/mar10/fancytree/wiki/TutorialLoadDat

Desafortunadamente mi cerebro ha dejado de funcionar hoy. No puedo ver una manera elegante.

Cualquier puntero sería muy apreciado.

Así que resolví esto eventualmente usando una publicación de Oskar

function getNestedChildren(arr, parent) {
    var out = []
    for(var i in arr) {
        if(arr[i].parent == parent) {
            var children = getNestedChildren(arr, arr[i].id)

            if(children.length) {
                arr[i].children = children
            }
            out.push(arr[i])
        }
    }
    return out
}

http: //oskarhane.com/create-a-nested-array-recursively-in-javascript

Esto construye la matriz anidada.

Para garantizar que los valores inferidos estaban presentes (por ejemplo, EE. UU., Que está en la jerarquía pero no es un valor único).

		var CountryArray = CountryText.split("|");
	
		// Variables to hold details of each section of the Country path being iterated
		var CountryId = '';
		var CountryParentPrefix = '';
		var CountryParent = '';

		// Iterate each section of the delimeted Country path and ensure that it is in the array
		for(var i in CountryArray) 
		{

			var CountryId = CountryParentPrefix+CountryArray[i];
	
			// Find the Country id in the array / add if necessary
			var result = FlatSource.filter(function (Country) { return Country.id == CountryId });
			if (result.length == 0) {
					// If the Country is not there then we should add it
					var arrCountry = {title:CountryArray[i], parent:CountryParent, id:CountryId};
					FlatSource.push(arrCountry);
			}
			

			// For the next path of the heirarchy
			CountryParent = CountryId;
			CountryParentPrefix = CountryId+'|';
		}

No utilicé la sugerencia de Sven pero sospecho que es igualmente válida.

Respuestas a la pregunta(1)

Su respuesta a la pregunta