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)
为了
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配合得很好。
最明智的做法是创建一个字典对象,而不是尝试分配给一堆单独的变量。您可以在这里轻松做到这一点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)
当然,您需要确保原始数组包含合理的值。