我有一个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()方法?
在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
截至2018年,有一个更短、更优雅的解决方案。使用即可。Array.prototype.sort()。
例子:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
简单答案:
objs.sort((a,b)=>a.last_nom.localeCompare(b.last_nom))
细节:
今天非常简单,您可以将字符串与localeCompare进行比较。正如Mozilla Doc所说:
localeCompare()方法返回一个数字,指示引用字符串在排序顺序上位于给定字符串之前、之后或与给定字符串相同。
//example1:
console.log("aaa".localeCompare("aab")); //-1
console.log("aaa".localeCompare("aaa")); //0
console.log("aab".localeCompare("aaa")); //1
//example2:
const a = 'réservé'; // with accents, lowercase
const b = 'RESERVE'; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// expected output: 0
有关详细信息,请参阅Mozilla doclocaleCompare:
在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