我有一个数组,我在数组中存储逗号分隔的字符串。现在我想从逗号分隔的字符串中取出每个第一个字母的字符串
对于ex => Abc, Xyz, Hji
现在我想要A, X, H
。
下面列出了我的代码和数组。
这是我的代码=>
var ArryString = [];
for (var i = 0; i < data.length; i++) {
ArryString.push(data[i].Str);
}
当前o / p =&gt;
"Abc"
"Xyz,Hji,Lol",
"Uyi,Mno"
my expacted o / p =&gt;
"A"
"X,H,L"
"U,M"
答案 0 :(得分:5)
您可以拆分字符串并仅使用destructuring assignment的第一个字符并加入字符串的第一个字符。然后将新字符串映射为新数组。
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
result = data.map(s => s
.split(',')
.map(([c]) => c)
.join());
console.log(result);
&#13;
答案 1 :(得分:1)
您可以使用charAt方法返回字符串的第一个字符。
var newString = [];
for (var i=0; i< newString.length; i++)
{
newString.push(ArrayString[i].charAt(0);
}
答案 2 :(得分:1)
对阵列中的每个字符串使用 String.charAt()方法,并将推送第一个字符添加到新数组中。
示例功能: -
function takeFirstChar(arr){
var new_arr = [];
arr.forEach(function(el){
var firstLetter = el.charAt(0)
new_arr.push(firstLetter);
});
return new_arr;
}
takeFirstChar(['hello','cruel','world']);
//Output-> ['h','c','w']
答案 3 :(得分:1)
这是一个有效的例子:
// We've got an array of comma separated worlds
// Sometimes we've got one, sometimes several
data=["Hello","i","have","one,array","and,i","store","comma,separated,string,in","the","array"];
// We want to ouput the same pattern but keeping the initial letter only
var result = [];
var items = [];
var aChar;
// We loop thru the data array
for (var i = 0; i < data.length; i++) {
// We make a small array with the content of each cell
items = data[i].split(",");
for (var j = 0; j < items.length; j++) { // We loop thru the items array
aChar = items[j].charAt(0); // We take the first letter only
if (aChar!="") // If the item/work was not empty the we keep only the initial letter in our items array
items[j] = aChar;
}
result.push(items.join(",")); // we store comma separated first letters in our result array
}
console.log(result)
&#13;
答案 4 :(得分:1)
这看起来并不好看,也不容易理解。
List
&#13;