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

时间:2018-04-15 00:28:56

标签: 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']

3 个答案:

答案 0 :(得分: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; }




答案 1 :(得分:2)

最明智的做法是创建一个字典对象,而不是尝试分配给一堆个别变量。您可以使用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'])




当然,您希望确保原始数组具有合理的值。

答案 2 :(得分:1)

对于单词= [“ 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配合得很好。