gpt4 book ai didi

javascript - 如何在Javascript中按字母顺序将字符串数组拆分为数组集

转载 作者:行者123 更新时间:2023-12-03 22:57:51 25 4
gpt4 key购买 nike

给定一个字符串数组,如何按字母顺序将这些字符串拆分为不同的数组?

例子:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com