我有一个JavaScript对象数组:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
如何在 JavaScript 中按 的值对它们进行排序?last_nom
我知道,但这似乎只适用于字符串和数字。是否需要向对象添加方法?sort(a,b)
toString()
网友回答:
您还可以创建一个动态排序函数,该函数按您传递的对象值对对象进行排序:
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
/* next line works with strings and numbers,
* and you may want to customize it to your needs
*/
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
因此,您可以拥有如下所示的对象数组:
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
…当您执行以下操作时,它将起作用:
People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));
实际上,这已经回答了这个问题。下面的部分是因为很多人联系我,抱怨它不适用于多个参数。
您可以使用下面的函数生成具有多个排序参数的排序函数。
function dynamicSortMultiple() {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
这将使您能够执行以下操作:
People.sort(dynamicSortMultiple("Name", "-Surname"));
对于我们当中可以使用ES6的幸运儿,它允许扩展本机对象:
class MyArray extends Array {
sortBy(...args) {
return this.sort(dynamicSortMultiple(...args));
}
}
这将实现:
MyArray.from(People).sortBy("Name", "-Surname");
网友回答:
编写自己的比较函数非常简单:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
或内联(c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
或简化为数字(c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
网友回答:
在 ES6/ES2015 或更高版本中,您可以通过以下方式执行此操作:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
在 ES6/ES2015 之前
objs.sort(function(a, b) {
return a.last_nom.localeCompare(b.last_nom)
});
模板简介:该模板名称为【按字符串属性值对对象数组进行排序】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。