JS array object - Chinese sorted by the first letter (grouping) sort(), localeCompare()

JS array object - Chinese is sorted by the first letter (sort, localeCompare)

Previous similar articles

Article content article link
JS array object——Sort by dateSort by time in ascending or descending order https://blog.csdn.net/XSL_HR/article/details/128579840?spm=1001.2014.3001.5501
JS array object——English sorted by the first letter https://blog.csdn.net/XSL_HR/article/details/128579936?spm=1001.2014.3001.5501

Scene recurrence

Sorting is very practical in projects, and it occurs very frequently, especially in the background management system , which requires us to display, process, and operate a large amount of data . generallyGet the array object from the background,ThenSort data in ascending or descending order according to one of the attributesprocessing.

The following will give an example in detail-Chinese is sorted according to the first letter

There are two methods of sorting in Chinese:

  • Using the sort and localCompare methodsto fulfill;
  • Import method from outside, using the methodsorting and grouping

Sort by Chinese initials

1. Alphabetical sorting

The method used for sorting : The localeCompare() method returns a number indicating whether a reference string is before or after the sort order or is the same as the given string. (The sorting method has been introduced in previous articles)

(1) Array content

// 根据id值的首字母进行排序
let arr = [
         {
    
    id:'sh',name:'上海'},
         {
    
    id:'bj',name:'北京'},
         {
    
    id:'gz',name:'广东'},
         {
    
    id:'sz',name:'深圳'}
      ]
// 根据中文首字母排序
let arr1 = ['上海','北京','广州','深圳']

(2)key code

// 根据id值的首字母排序
arr.sort((a, b) => a['id'].localeCompare(b['id']))
console.log(arr)
// 根据中文的首字母排序
arr1.sort((a, b) => a.localeCompare(b))
console.log(arr1)

(3) Console sorting results
insert image description here
insert image description here

2. Sort and group

In the front-end development process, sorting and grouping according to the first letter of Chinese characters is a very common operation, such ascontact listIntroduce third-party plug-ins
Create a new terminal in the folder where the project is located, and enter the following code to import the plugin( The premise is that node.js has been installed )

npm i --save jian-pinyin

Introduce in the vue page that needs to be used

import Pinyin from 'js-pinyin'

Encapsulates a function with sorting and grouping functionality( Refer to the following sortByFirstLetter code )

function sortByFirstLetter(origin) {
    
    
    // 将目标数据进行排序
    origin = origin.sort((pre, next) => Pinyin.getFullChars(pre).localeCompare(Pinyin.getFullChars(next)))
    const newArr = []
    origin.map(item => {
    
    
        // 取首字母
        const key = Pinyin.getFullChars(item).charAt(0)
        const index = newArr.findIndex(subItem => subItem.key === key)
        if (index < 0) {
    
    
            newArr.push({
    
    
                key: key,
                list: [item]
            })
        } else {
    
    
            newArr[index].list.push(item)
        }
    })
    return newArr
}

array content

const originData = [
        '上饶', '上海', '深圳', '广州', '武汉', '十堰', '天津', '北京'
    ]
console.log(sortByFirstLetter(originData)) // 控制台打印结果

Sorted results: ( both sorting and grouping are completed )

[
    {
    
     key: 'B', list: ['北京'] },
    {
    
     key: 'G', list: ['广州'] },
    {
    
     key: 'S', list: ['上海', '上饶', '深圳', '十堰'] },
    {
    
     key: 'T', list: ['天津'] },
    {
    
     key: 'W', list: ['武汉'] }
]

The next article will introduce how to convert the time in digital format (2022-12-22) to the date in Chinese character format (December 22, 2022), and even the full Chinese character format (December 2, 2022) used in the certificate 12th) Date~
Interested friends can subscribe to this column to facilitate follow-up learning~
Friends who find this article useful can like it ➕ bookmark ➕ follow it~

Guess you like

Origin blog.csdn.net/XSL_HR/article/details/128580085