sort()、localeCompare()排序的使用

数组类型

let arr = ['上海','北京','广州','深圳']

arr.sort((a, b) => a.localeCompare(b))

// sort()方法会改变原数组
console.log(arr) // ['北京', '广州', '上海', '深圳']

数组元素为对象类型

let arr = [
  {EName:'sh',CName:'上海'},
  {EName:'bj',CName:'北京'},
  {EName:'gz',CName:'广东'},
  {EName:'sz',CName:'深圳'}
]
// 根据EName值的首字母进行排序
arr.sort((a, b) => a['EName'].localeCompare(b['EName']))
console.log(arr)
/*
	[{EName: 'bj', CName: '北京'},
	{EName: 'gz', CName: '广东'},
	{EName: 'sh', CName: '上海'},
	{EName: 'sz', CName: '深圳'}]
*/

// 根据CName值的首字母进行排序
arr.sort((a, b) => a['CName'].localeCompare(b['CName']))
console.log(arr)
/*
	[{EName: 'bj', CName: '北京'},
	{EName: 'gz', CName: '广东'},
	{EName: 'sh', CName: '上海'},
	{EName: 'sz', CName: '深圳'}]
*/

你可能感兴趣的:(javascript,前端,开发语言)