我有一个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()方法?
如果您有嵌套对象
const objs = [{
first_nom: 'Lazslo',
last_nom: 'Jamf',
moreDetails: {
age: 20
}
}, {
first_nom: 'Pig',
last_nom: 'Bodine',
moreDetails: {
age: 21
}
}, {
first_nom: 'Pirate',
last_nom: 'Prentice',
moreDetails: {
age: 22
}
}];
nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
const a = prop2 ? e1[prop1][prop2] : e1[prop1],
b = prop2 ? e2[prop1][prop2] : e2[prop1],
sortOrder = direction === "asc" ? 1 : -1
return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
}
并称之为
objs.sort(nestedSort("last_nom"));
objs.sort(nestedSort("last_nom", null, "desc"));
objs.sort(nestedSort("moreDetails", "age"));
objs.sort(nestedSort("moreDetails", "age", "desc"));
Lodash(Undercore.js的超集)。
不为每一个简单的逻辑添加一个框架是很好的,但是依赖于经过良好测试的实用程序框架可以加快开发并减少错误数量。
Lodash生成了非常干净的代码,并促进了更具功能性的编程风格。一眼望去,代码的意图就一目了然了。
OP的问题可以简单地解决为:
const sortedObjs = _.sortBy(objs, 'last_nom');
更多信息?例如,我们有以下嵌套对象:
const users = [
{ 'user': {'name':'fred', 'age': 48}},
{ 'user': {'name':'barney', 'age': 36 }},
{ 'user': {'name':'wilma'}},
{ 'user': {'name':'betty', 'age': 32}}
];
我们现在可以使用_.properties速记user.age来指定应该匹配的属性的路径。我们将根据嵌套的年龄属性对用户对象进行排序。是的,它允许嵌套属性匹配!
const sortedObjs = _.sortBy(users, ['user.age']);
想要反转吗?没问题。使用_反向。
const sortedObjs = _.reverse(_.sortBy(users, ['user.age']));
想用链条将两者结合起来吗?
const { chain } = require('lodash');
const sortedObjs = chain(users).sortBy('user.age').reverse().value();
或者你什么时候更喜欢流动而不是链条?
const { flow, reverse, sortBy } = require('lodash/fp');
const sortedObjs = flow([sortBy('user.age'), reverse])(users);
我将给您一个实现选择排序算法的解决方案。它简单有效。
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);