2017-08-06 10 views
-4

我在JavaScript中有一個問題。 我試着解釋我想要做什麼。 我從API獲取元素。數組與字符串 - 如何拆分字符串

這裏是數組,我回去

["Caribbean, Cuban", "Thai", "Italian, Pizza", "Asian, Japanese", "American, 
BBQ, Desserts", "Italian, Pizza", "Indian", "Asian", "Indian"] 

我需要的是:

["Caribbean", "Cuban", "Thai", "Italian", "Pizza", "Asian", "Japanese", "American", 
"BBQ", "Desserts", "Italian", "Pizza", "Indian", "Asian", "Indian"] 

,你可以在第二陣列中所看到的每一個串元素已經分裂。第一個數組有9個元素,而第二個數組有15個元素。

謝謝

+2

在哪個編程語言中編碼?你到目前爲止嘗試過什麼? – Gustavo

回答

2
  1. 創建一個新的空數組
  2. 循環通過你得到了來自API
  3. 回用逗號分割字符串到一個數組
  4. 添加此數組中的所有值的數組進入外部陣列
1

因爲你沒有提到任何語言,我會寫在JS然後你適應:

var a = ["Caribbean, Cuban", "Thai", "Italian, Pizza", "Asian, Japanese", "American, BBQ, Desserts", "Italian, Pizza", "Indian", "Asian", "Indian"]; 
var b=[]; 
a.forEach(function(entry) { 
    if (entry.indexOf(", ") >= 0){ 
var res = entry.split(", "); 
b.push(res[0]); 
b.push(res[1]); 
if(res[2]){b.push(res[2]);} 
} else { 
b.push(entry); 
} 
});