sort 数组对象排序_使用sort(fn)按属性对对象数组进行排序

sort 数组对象排序

Believe it or not, there's more to JavaScript than the helper methods and classes they provide your JavaScript library. No, like seriously bro; these JavaScript-given methods do exist. One of those methods, sort, is provided to every Array instance via its prototype. I've used this method once or twice in the history of ever, bro, since I make every effort to ensure proper sort on the server side, but sometimes you may receive a JSON dump and need to sort on the client side.

信不信由你,JavaScript提供给您JavaScript库之外的辅助方法和类还比JavaScript多得多。 不,像兄弟一样认真; 这些JavaScript提供的方法确实存在。 这些方法之一是sort,通过其原型提供给每个Array实例。 我在兄弟的历史上曾经使用过这种方法一次或两次,因为我已尽一切努力确保在服务器端进行正确的排序,但是有时您可能会收到JSON转储,并且需要在客户端进行排序。

Most people would assume that sort would take no method and simply sort the basic items within the array:

大多数人会认为sort不会采用任何方法,而只是对数组中的基本项进行排序:


[1, 3, 9, 2].sort();
	// Returns: [1, 2, 3, 9]
	
[1, "a", function(){}, {}, 12, "c"].sort();
	// Returns: [1, 12, Object, "a", "c", function (){}]


But nay, broseph! If you provide a function expression to the sort method, you can sort objects within the array using simple logic. Let's say you have an array of objects representing persons and you want to sort them by age. Oh yes, it can be done, and quite easily:

但是,不,broseph! 如果为sort方法提供函数表达式,则可以使用简单逻辑对数组中的对象进行排序。 假设您有一系列代表人物的对象,并且想按年龄对它们进行排序。 哦,是的,可以很容易地做到这一点:


[
	{ name: "Robin Van Persie", age: 28 },
	{ name: "Theo Walcott", age: 22 },
	{ name: "Bacary Sagna", age: 26  }
].sort(function(obj1, obj2) {
	// Ascending: first age less than the previous
	return obj1.age - obj2.age;
});
	// Returns:  
	// [
	//	  { name: "Theo Walcott", age: 22 },
	//	  { name: "Bacary Sagna", age: 26  },
	//	  { name: "Robin Van Persie", age: 28 }
	// ]
	


The anonymous function returns whether or not the first object's age is less than the second's, thus sorting the entire array in ascending order by age. Reverse the first and second arguments to sort in descending order.

匿名函数返回第一个对象的年龄是否小于第二个对象的年龄,从而按年龄升序对整个数组进行排序。 反转第一个和第二个参数以降序排列。

So brochacho, now you know how to sort an array of objects using JavaScript. Get to it!

因此,brochacho,现在您知道如何使用JavaScript对对象数组进行排序。 来吧!

翻译自: https://davidwalsh.name/array-sort

sort 数组对象排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值