Data alphabetic index sort of JS.


For address book or product list

1. Before sorting

{[ ],[ ],[ ]}

2. After sorting

{A:{},B:{},C:{}}

在这里插入图片描述

//Processing data is sorted alphabetically.
			 sortData(data,field){//Data original data, Pinyin key name of field data.
				let letter_reg = /^[A-Z]$/;
				let list = [];
				let letter = '';
				for (let i = 0; i < data.length; i++) {
					//Add ා group to store data whose initial cannot be converted to uppercase English
					list['#'] = [];
					//Initial to capital English
					letter = (data[i][field]).slice(0, 1).toUpperCase();
					//Capitalized or not
					if (!letter_reg.test(letter)) {
						letter = '#';
					}
					//Create letter groups
					if (!(letter in list)) {
						list[letter] = [];
					}
					//Letter grouping add data
					list[letter].push(data[i]);
				}
				//Transform the format to sort;
				let resault = [];
				for (let key in list) {
					resault.push({
						letter: key,
						list: list[key]
					});
				}
				resault.sort((a,b) => {
					return a.letter.charCodeAt(0) - b.letter.charCodeAt(0);
				});
				//Put the number group last
				let last_arr = resault[0];
				resault.splice(0, 1);
				resault.push(last_arr);
			 
				//Convert data format
				let json_sort = {}
				for (let i = 0; i < resault.length; i++) {
					json_sort[resault[i].letter] = resault[i].list;
				}
			 
				return resault;
			}

Leave a Reply