sort()排序数组以及数组对象
一般排序
//sort.js
var arr = ['go','javascript','java','c','python','c++','--','c+d', '5', 1, '12']
console.log(arr.sort())
$ node sort.js
[
'--', 1,
'12', '5',
'c', 'c++',
'c+d', 'go',
'java', 'javascript',
'python'
]
//很明显是根据里面每一项从头到尾每一位进行排序的。这里不细究内部算法实现。
比较排序
// 比较适合排序数字,不管是字符串的形式还是数字
var arr1 = [11, 54, 34, 24, 36, 78, 12, '13']
console.log(arr1.sort((a,b) => a-b))
/*[
11, 12, '13',
24, 34, 36,
54, 78
] */
var arr = ['go','javascript','java','c','python','c++','--','c+d', 11,'1c', 54, '3v',34,'3d', 24, 36, 78, 12, '13','1d']
console.log(arr.sort((a,b) => a-b))
/*
[
'go', 'javascript',
'java', 'c',
'python', 'c++',
'--', 'c+d',
11, '1c',
54, '3v',
34, '3d',
12, '13',
24, 36,
78, '1d'
]
*/
根据数组中每个对象的某个key所对应的value(数字)排序
var arr = [
{
go: 11,
to: 'asd'
},
{
go: 54,
to: 'asd'
},
{
go: 34,
to: 'asd'
},
{
go: 24,
to: 'asd'
},
{
go: 78,
to: 'asd'
},
{
go: 12,
to: 'asd'
},
{
go: '13',
to: 'asd'
},
]
console.log(arr.sort((a,b) => a.go - b.go))
console.log(arr.sort((a,b) => b.go - a.go))
/*
[
{ go: 11, to: 'asd' },
{ go: 12, to: 'asd' },
{ go: '13', to: 'asd' },
{ go: 24, to: 'asd' },
{ go: 34, to: 'asd' },
{ go: 54, to: 'asd' },
{ go: 78, to: 'asd' }
]
[
{ go: 78, to: 'asd' },
{ go: 54, to: 'asd' },
{ go: 34, to: 'asd' },
{ go: 24, to: 'asd' },
{ go: '13', to: 'asd' },
{ go: 12, to: 'asd' },
{ go: 11, to: 'asd' }
]
*/
根据对象数组中某个key所对应value(字符串)的首字母大写所对应的Unicode编码排序
var arr = [
{
go: 'go',
to: 'asd'
},
{
go: 'javascript',
to: 'asd'
},
{
go: 'java',
to: 'asd'
},
{
go: 'c',
to: 'asd'
},
{
go: 'python',
to: 'asd'
},
{
go: 'c++',
to: 'asd'
},
{
go: '--',
to: 'asd'
},
{
go: 'c+d',
to: 'asd'
},
{
go: '1c',
to: 'asd'
}
]
console.log(arr.sort((a,b) => a.go[0].toUpperCase().charCodeAt() - b.go[0].toUpperCase().charCodeAt()))
console.log(arr.sort((a,b) => b.go[0].toUpperCase().charCodeAt() - a.go[0].toUpperCase().charCodeAt()))
// 只会根据第一个,第二个是不固定的
/*[
{ go: '--', to: 'asd' },
{ go: '1c', to: 'asd' },
{ go: 'c', to: 'asd' },
{ go: 'c++', to: 'asd' },
{ go: 'c+d', to: 'asd' },
{ go: 'go', to: 'asd' },
{ go: 'javascript', to: 'asd' },
{ go: 'java', to: 'asd' },
{ go: 'python', to: 'asd' }
]
[
{ go: 'python', to: 'asd' },
{ go: 'javascript', to: 'asd' },
{ go: 'java', to: 'asd' },
{ go: 'go', to: 'asd' },
{ go: 'c', to: 'asd' },
{ go: 'c++', to: 'asd' },
{ go: 'c+d', to: 'asd' },
{ go: '1c', to: 'asd' },
{ go: '--', to: 'asd' }
] */
reverse()反转数组
var arr = ['go','javascript','java','c','python','c++','--','c+d', '5', 1, '12']
console.log(arr.reverse())
$ node reverse.js
[
'12', 1,
'5', 'c+d',
'--', 'c++',
'python', 'c',
'java', 'javascript',
'go'
]
// 字面意思的反转