我有一个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()方法?
使用JavaScript排序方法
排序方法可以修改为使用比较函数对数字、字符串甚至对象数组进行排序。
比较函数作为可选参数传递给排序方法。
此比较函数接受两个参数,通常称为a和b。根据这两个参数可以修改排序方法,使其按需工作。
如果compare函数返回的值小于0,那么sort()方法将a排序到比b低的索引。如果compare函数返回的值等于0,那么sort()方法将保持元素位置不变。如果compare函数返回的值大于0,那么sort()方法会以大于b的索引对a进行排序。
使用上述概念应用于对象,其中a将是对象属性。
var对象=[{first_nom:'Lazslo',last_nom:'Jamf'},{first_nom:'猪',last_nom:'Bodine'},{first_nom:'海盗',last_nom:'Prentice'}];函数比较(a,b){如果(a.last_nom>b.last_nom)返回1;如果(a.last_nom<b.last_nom)返回-1;返回0;}objs.sort(比较);console.log(对象)//要获得更好的外观,请使用console.table(objs)
使用JavaScript排序方法
排序方法可以修改为使用比较函数对数字、字符串甚至对象数组进行排序。
比较函数作为可选参数传递给排序方法。
此比较函数接受两个参数,通常称为a和b。根据这两个参数可以修改排序方法,使其按需工作。
如果compare函数返回的值小于0,那么sort()方法将a排序到比b低的索引。如果compare函数返回的值等于0,那么sort()方法将保持元素位置不变。如果compare函数返回的值大于0,那么sort()方法会以大于b的索引对a进行排序。
使用上述概念应用于对象,其中a将是对象属性。
var对象=[{first_nom:'Lazslo',last_nom:'Jamf'},{first_nom:'猪',last_nom:'Bodine'},{first_nom:'海盗',last_nom:'Prentice'}];函数比较(a,b){如果(a.last_nom>b.last_nom)返回1;如果(a.last_nom<b.last_nom)返回-1;返回0;}objs.sort(比较);console.log(对象)//要获得更好的外观,请使用console.table(objs)
尝试以下方式:
let objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
const compareBylastNom = (a, b) => {
// Converting to uppercase to have case-insensitive comparison
const name1 = a.last_nom.toUpperCase();
const name2 = b.last_nom.toUpperCase();
let comparison = 0;
if (name1 > name2) {
comparison = 1;
} else if (name1 < name2) {
comparison = -1;
}
return comparison;
}
console.log(objs.sort(compareBylastNom));
我没有看到任何类似于我的实现。此版本基于施瓦茨变换习惯用法。
function sortByAttribute(array, ...attrs) {
// Generate an array of predicate-objects containing
// property getter, and descending indicator
let predicates = attrs.map(pred => {
let descending = pred.charAt(0) === '-' ? -1 : 1;
pred = pred.replace(/^-/, '');
return {
getter: o => o[pred],
descend: descending
};
});
// Schwartzian transform idiom implementation. AKA "decorate-sort-undecorate"
return array.map(item => {
return {
src: item,
compareValues: predicates.map(predicate => predicate.getter(item))
};
})
.sort((o1, o2) => {
let i = -1, result = 0;
while (++i < predicates.length) {
if (o1.compareValues[i] < o2.compareValues[i])
result = -1;
if (o1.compareValues[i] > o2.compareValues[i])
result = 1;
if (result *= predicates[i].descend)
break;
}
return result;
})
.map(item => item.src);
}
下面是如何使用它的示例:
let games = [
{ name: 'Mashraki', rating: 4.21 },
{ name: 'Hill Climb Racing', rating: 3.88 },
{ name: 'Angry Birds Space', rating: 3.88 },
{ name: 'Badland', rating: 4.33 }
];
// Sort by one attribute
console.log(sortByAttribute(games, 'name'));
// Sort by mupltiple attributes
console.log(sortByAttribute(games, '-rating', 'name'));