我有一个JavaScript对象数组:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
如何在JavaScript中按last_nom的值对它们进行排序?
我知道排序(a,b),但这似乎只适用于字符串和数字。是否需要向对象添加toString()方法?
我将给您一个实现选择排序算法的解决方案。它简单有效。
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
function selection_Sort(num) {
//console.log(num);
var temp, index;
for (var i = 0; i <= num.length - 1; i++) {
index = i;
for (var j = i + 1; j <= num.length - 1; j++) {
// You can use first_nom/last_nom, any way you choose to sort
if (num[j].last_nom < num[index].last_nom) {
index = j;
}
}
// Below is the swapping part
temp = num[i].last_nom;
num[i].last_nom = num[index].last_nom;
num[index].last_nom = temp;
};
console.log(num);
return num;
}
selection_Sort(objs);
一个按属性对对象数组进行排序的简单函数:
function sortArray(array, property, direction) {
direction = direction || 1;
array.sort(function compare(a, b) {
let comparison = 0;
if (a[property] > b[property]) {
comparison = 1 * direction;
} else if (a[property] < b[property]) {
comparison = -1 * direction;
}
return comparison;
});
return array; // Chainable
}
用法:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc
在TypeScript中编程时,也可以创建动态排序函数,但在这种情况下,类型变得更加复杂。
function sortByKey<O>(key: keyof O, decending: boolean = false): (a: O, b: O) => number {
const order = decending ? -1 : 1;
return (a, b): number => {
const valA = a[key];
const valB = b[key];
if (valA < valB) {
return -order;
} else if (valA > valB) {
return order;
} else {
return 0;
}
}
}
这可以在TypeScript中使用,如下所示:
const test = [
{
id: 0,
},
{
id: 2,
}
]
test.sort(sortByKey('id')) // OK
test.sort(sortByKey('id1')) // ERROR
test.sort(sortByKey('')) // ERROR