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

Chr*_* R. 3 javascript arrays sorting

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

例子:

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']
Run Code Online (Sandbox Code Playgroud)

Gab*_* P. 6

为了

let words = ["corn", "to", "add", "adhere", "tree"]
Run Code Online (Sandbox Code Playgroud)

这样做

  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;
      }, {})
    );
 }
Run Code Online (Sandbox Code Playgroud)

将产生一个很好的分组,例如,

[{title: 'T', data: ["to", "tree"]}, ...]
Run Code Online (Sandbox Code Playgroud)

这与SectionListReactNative配合得很好。


Mar*_*yer 5

最明智的做法是创建一个字典对象,而不是尝试分配给一堆单独的变量。您可以在这里轻松做到这一点reduce()

let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana', 'yam', 'yucca']

let dict = array.reduce((a, c) => {
    // c[0] should be the first letter of an entry
    let k = c[0].toLocaleUpperCase()

    // either push to an existing dict entry or create one
    if (a[k]) a[k].push(c)
    else a[k] = [c]

    return a
}, {})

console.log(dict)

// Get the A's
console.log(dict['A'])
Run Code Online (Sandbox Code Playgroud)

当然,您需要确保原始数组包含合理的值。

  • @克里斯托弗R。你几乎可以做同样的事情,但是在reduce中,你需要提取你想要的特定属性——比如:`k = c['fruit'][0].toUppercase`和` a[k].push(c['水果'])` (2认同)