/**
*
* @param array 需要排序的數(shù)組吼旧。['a','哇']
* @param key 需要返回的數(shù)組key
*/
function sort(array, key) {
if(!key.toLocaleLowerCase().match(/[a-z]/ || !Array.isArray(array) || array.length === 0)) {
throw Error('傳的參數(shù)有問題')
}
function compare(a, b) {
return a.localeCompare(b, 'zh-CN')
}
const letters = 'abcdefghjklmnopqrstwxyz'.split(''),
zh = '阿八嚓噠妸發(fā)旮哈譏咔垃痳拏噢妑七呥扨它穵夕丫帀'.split(''),
index = key && letters.indexOf(key.toLocaleLowerCase()),
result = []
array.forEach(value => {
if(value[0].toLocaleLowerCase() === key.toLocaleLowerCase() || compare(zh[index],value[0]) <= 0 && (!zh[index + 1] || compare(value[0], zh[index+1]) < 0)) {
result.push(value)
}
})
result.sort((a, b) => compare(a, b))
return result
}
console.log(sort(['aaa','bb','a', '哇','吧','這','啊','阿','錒','aaa','abc','bc'], 'a'))
//["阿", "錒", "啊", "a", "aaa", "aaa", "abc"]
此函數(shù)的關(guān)鍵就是localeCompare函數(shù)畜眨。在stackoverflow提問中乘陪,有人提到要用到a.localeCompare(b,'zh-CN'),其中"zh-CN",特別重要冰更。這個(gè)參數(shù)使localeCompare函數(shù)使用中文拼音規(guī)則進(jìn)行比較大小产徊。
還有zh數(shù)組,這是我在網(wǎng)上另外一篇博客中取得蜀细,這個(gè)數(shù)組的作用就是取到拼音對應(yīng)的最小文字舟铜。阿就是拼音a對應(yīng)的最小中文字符(使用localeCompare進(jìn)行比較時(shí))。但我無法保證這個(gè)數(shù)組中的每一個(gè)字符都是對應(yīng)拼音最小的字符奠衔。在網(wǎng)上的博客中沒有一個(gè)人能說明這個(gè)數(shù)組中的數(shù)據(jù)為什么正確谆刨。我本人也沒有找到相關(guān)資料,所以只能暫且使用這些數(shù)據(jù)归斤。