Lin*_*yen 1 javascript arrays grouping
我目前正在研究javascript,并且在尝试弄清楚如何处理此问题时遇到问题:
我有这样的带有特殊问号的单词数组
wordsArray = [“为什么”,“会”,“您”,“付款”,“用于”,“一个”,“电话”,“?”];
我试图在数组的同一单独组中将具有相同起始字符的单词分组,示例输出将是:
firstArray = ["why", "would"] //<- all start with w
secondArray = ["you"]
thirdArray = ["pay", "phone"]//<- all start with p
fourthArray = ["for"]
fifthArray = ["a"]
finalArray = ["?"]//<- special character like ?, :,.. in the same group
Run Code Online (Sandbox Code Playgroud)
我该如何实现?我写错了这个问题,看起来好像我在问代码,但是我实际上是在寻求解决方案,以解决这个问题(逻辑上)
您可以使用Array.reduce
const wordsArray = ["why", "would", "you", "pay", "for", "a", "phone", "?"];
const binned = wordsArray.reduce((result, word) => {
// get the first letter. (this assumes no empty words in the list)
const letter = word[0];
// ensure the result has an entry for this letter
result[letter] = result[letter] || [];
// add the word to the letter index
result[letter].push(word);
// return the updated result
return result;
}, {})
console.log(binned);Run Code Online (Sandbox Code Playgroud)