作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定一个字符串数组,如何按字母顺序将这些字符串拆分为不同的数组?
例子:
let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana', 'yam', 'yucca']
// return should be something like:
a = ['apple', 'acorn']
b = ['banana', 'beet']
c = ['cheese', 'corn']
y = ['yam', 'yucca']
最佳答案
为了
let words = ["corn", "to", "add", "adhere", "tree"]
这样做
const getSections = () => {
if (words.length === 0) {
return [];
}
return Object.values(
words.reduce((acc, word) => {
let firstLetter = word[0].toLocaleUpperCase();
if (!acc[firstLetter]) {
acc[firstLetter] = { title: firstLetter, data: [word] };
} else {
acc[firstLetter].data.push(word);
}
return acc;
}, {})
);
}
将产生一个很好的分组,例如,
[{title: 'T', data: ["to", "tree"]}, ...]
这与
SectionList
非常吻合在 ReactNative 中。
关于javascript - 如何在Javascript中按字母顺序将字符串数组拆分为数组集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49837432/
我是一名优秀的程序员,十分优秀!