之前在其他地方看的zh字母分类列表不对,导致部分排序错误,特此记录
最重要的首拼汉字列表: 阿八嚓耷妸发旮哈丌咔垃妈嗯喔妑七呥仨他穵夕丫帀
// sourceData: [{ id: restaurant.id, name: restaurant.name, available: true }, ...]
function formatCommonData(sourceData) {
let childrens = {};
if (sourceData.length > 0) {
const result = [];
const defaultIndexes = [{ i: 9, data: ['i'] }, { i: 21, data: ['v', 'u'] }];
const letters = '*abcdefghjklmnopqrstwxyz'.split('');
const zh = '阿八嚓耷妸发旮哈丌咔垃妈嗯喔妑七呥仨他穵夕丫帀'.split('');
const english = new RegExp('[A-Za-z]+');
letters.forEach((letter, index) => {
const current = { index: letter.toUpperCase(), childrens: [] };
sourceData.forEach((item) => {
let matched = false;
if (english.test(item.name.substr(0, 1))) {
matched = item.name.length > 0 && item.name.charAt(0).toUpperCase() === letter.toUpperCase();
} else {
// localeCompare需要加参数 'zh', 不然在英文环境下,无法正常工作
matched = (!zh[index - 1] || zh[index - 1].localeCompare(item.name, 'zh') <= 0) && item.name.localeCompare(zh[index], 'zh') === -1;
}
if (matched) {
current.childrens.push({ id: item.id, name: item.name, available: true });
}
});
result.push(JSON.parse(JSON.stringify(current)));
});
defaultIndexes.forEach((index) => {
index.data.forEach((x) => {
const list = sourceData.filter((item) => item.name.length > 0 && item.name.charAt(0).toUpperCase() === x.toUpperCase());
const temp = [];
list.forEach((item) => {
temp.push({ id: item.id, name: item.name, available: true });
});
result.splice(index.i, 0, { index: x.toUpperCase(), childrens: temp });
});
});
const last = result.filter((item) => item.childrens.length > 0);
last.forEach((item) => {
item.childrens.sort((a, b) => a.name.localeCompare(b.name, 'zh'));
});
childrens = { indexes: last.map((x) => x.index), data: last };
}
return childrens;
}
以上代码可以将 list 转为以下格式
{
indexes: ['B', 'H', 'L', 'S'],
data: [
{
index: 'B',
childrens: [
{ id: 1, name: '北京安立路', availabel: true },
{ id: 2, name: '北京百子湾', availabel: true }
]
},
{
index: 'H',
childrens: [
{ id: 3, name: '河北', availabel: true },
{ id: 4, name: '河南', availabel: true }
]
},
......
]
}