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

4
给定一个字符串数组,我该如何按字母顺序将这些字符串拆分成不同的数组?
例子:
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']

6
你目前为止尝试了什么? - Herohtar
3
如果你想要调试帮助,SO并不是你个人的代码编写服务 - 显示你尝试过什么。请展示你已经尝试过的内容。 - CertainPerformance
你解决了这些场景吗? - Rajesh Sharma
3个回答

6

针对

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"]}, ...]

这很好地配合了ReactNative中的SectionList。

就像你读懂了我的想法。这正是我试图做的事情,也是出于同样的原因。这是一个非常好的解决方案,谢谢你。 - Christopher R.

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'])

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

1
非常感谢您的回答!这正好回答了我的问题。如果那个水果是对象数组中属性的值,我很想知道如何实现。[{id: 1, fruit: "apple"}, {id: 2, fruit: "banana"}] - Christopher R.
2
@ChristopherR. 你可以做几乎相同的事情,但是在 reduce 函数内部,你需要提取出你想要的特定属性,类似于:k = c['fruit'][0].toUppercasea[k].push(c['fruit']) - Mark

3
你还可以从数组中填充一个Map对象,并根据键(字符串的第一个字符)获取值:

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

let map = ((m, a) => (a.forEach(s => {
  let a = m.get(s[0]) || [];
  m.set(s[0], (a.push(s), a));
}), m))(new Map(), array);

console.log(map.get("a"));
console.log(map.get("b"));
console.log(map.get("c"));
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接