JSON对象字符串数组,多字段(多列)排序
今天看到我写的另一篇JSON对象数组排序的文章,突然想到了另一种,更简便,更快速的方法,排序结果跟原来的一样:
function newSort(objArr, keyArr, type) {
objArr.sort(function (objA, objB) {
for (let i = 0; i < keyArr.length; i++) {
var key = keyArr[i];
if (objA[key] === objB[key]) {
continue;
}
if (type === 'desc') {
return objA[key] < objB[key];
} else {
return objA[key] > objB[key];
}
}
});
return objArr;
}
// 测试数据
var arr = [
{
name: 'titanic',
addr: 'americ',
type: 'film',
size: 1024
},
{
name: 'hunting',
addr: 'china',
type: 'tv',
size: 10240
},
{
name: 'drunken',
addr: 'china',
type: 'film',
size: 2048
},
{
name: 'lifetimes',
addr: 'china',
type: 'tv',
size: 20
},
{
name: 'lifetimes',
addr: 'china',
type: 'tv',
size: 2
},
{
name: 'lifetimes',
addr: 'americ',
type: 'tv',
size: 204
},
{
name: 'lifetimes',
addr: 'americ',
type: 'film',
size: 20480
}
];
var newSort = newSort(JSON.parse(JSON.stringify(arr)), ['name', 'addr', 'type', 'size'], 'desc');
console.log('排序前:');
console.log(arr);
console.log('新排序:');
console.log(newSort);
打印结果
排序前:
[ { name: 'titanic', addr: 'americ', type: 'film', size: 1024 },
{ name: 'hunting', addr: 'china', type: 'tv', size: 10240 },
{ name: 'drunken', addr: 'china', type: 'film', size: 2048 },
{ name: 'lifetimes', addr: 'china', type: 'tv', size: 20 },
{ name: 'lifetimes', addr: 'china', type: 'tv', size: 2 },
{ name: 'lifetimes', addr: 'americ', type: 'tv', size: 204 },
{ name: 'lifetimes', addr: 'americ', type: 'film', size: 20480 } ]
新排序:
[ { name: 'titanic', addr: 'americ', type: 'film', size: 1024 },
{ name: 'lifetimes', addr: 'china', type: 'tv', size: 20 },
{ name: 'lifetimes', addr: 'china', type: 'tv', size: 2 },
{ name: 'lifetimes', addr: 'americ', type: 'tv', size: 204 },
{ name: 'lifetimes', addr: 'americ', type: 'film', size: 20480 },
{ name: 'hunting', addr: 'china', type: 'tv', size: 10240 },
{ name: 'drunken', addr: 'china', type: 'film', size: 2048 } ]