对象数组排序 [英] Sort array of objects

查看:34
本文介绍了对象数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象文字数组:

I have an array of object literals like this:

var myArr = [];

myArr[0] = {
   'score': 4,
   'name': 'foo'
}

myArr[1] = {
   'score': 1,
   'name': 'bar'
}

myArr[2] = {
   'score': 3,
   'name': 'foobar'
}

我将如何对数组进行排序,使其按 'score' 参数升序,使其变为:

How would I sort the array so it ascends by the 'score' parameter such that it would change to:

myArr[0] = {
   'score': 1,
   'name': 'bar'
}

myArr[1] = {
   'score': 3,
   'name': 'foobar'
}

myArr[2] = {
   'score': 4,
   'name': 'foo'
}

提前致谢.

推荐答案

Try myArr.sort(function (a, b) {return a.score - b.score});

数组元素的排序方式取决于传入的函数返回的数字:

The way the array elements are sorted depends on what number the function passed in returns:

  • <代码><0(负数):ab
  • 之前
  • <代码>>0(正数):ba
  • 前面
  • 0:在这种情况下,两个数字将在排序列表中相邻.但是,排序并不能保证稳定:ab 相对于彼此的顺序可能改变.
  • < 0 (negative number): a goes ahead of b
  • > 0 (positive number): b goes ahead of a
  • 0: In this cases the two numbers will be adjacent in the sorted list. However, the sort is not guaranteed to be stable: the order of a and b relative to each other may change.

这篇关于对象数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆