let str = 'B->A C->A D->B D->C D->E' //[A-B] [A-C] [B-D] [C-D] [E-D] //[A,E][B,C][D] let list = str.split(' ') list = list.map(item=> item.split('->').reverse()) let result = [[]] list.forEach( item=> { let start = item[0] let end = item[1] let index1 = result.findIndex( item => { return item.includes(start)}) let index2 = result.findIndex( item => { return item.includes(end)}) //start和end都不存在 if(index1 == -1 && index2 == -1){ result[0].push(start) if(!result[1]){ result[1] = [] } result[1].push(end) }else if( index1 == -1 && index2 > -1) { //start不存在 end存在 result[0].push(start) }else if( index1 > -1 ) { //start存在 result = result.map( item => item.filter(el=> el!=end)) //去掉end 再插入end if(!result[index1+1]){ result[index1+1] = [] } result[index1+1].push(end) } }) let arr = [] result.forEach( item => { arr = [...arr, ...item.sort()]; //同一层级默认字母排序 }) console.log(arr.join(' '))