简体   繁体   English

使用函数按值对JavaScript对象排序

[英]Using a function to sort JavaScript objects by values

So if i have an array of objects such as: 因此,如果我有一个对象数组,例如:

var a = [
  {
    name: "Apple",
    rank: 25
  },
  {
    name: "Cherry",
    rank: 29
  },
  {
    name: "Grape",
    rank: 15
  }
]

Is there a way to sort the values say by rank, by calling a function, i have had an attempt at it but keep getting undefined: 有没有一种方法可以通过调用函数来按等级对值进行排序,我曾尝试过但一直未定义:

function sorting(obj){
    obj.sort(function(a, b){
        return a[1] - b[1];
    })
}

I am struggling to find out where i am going wrong, and am unable to find any documents on MDN regarding this. 我正在努力找出问题所在,也无法在MDN上找到与此相关的任何文档。

Any help would be much appreciated, thanks in advance 任何帮助将不胜感激,在此先感谢

Both a and b that get passed to sort 's callback are the objects from the array. 传递给sort的回调的ab都是数组中的对象。 If you want to access their rank property you need to do a.rank not a[1] . 如果要访问他们的rank属性,则需要执行a.rank而不是a[1] Both a[1] and b[1] are undefined because the objects don't have a property called "1" : a[1]b[1]undefined因为对象没有名为"1"的属性:

return a.rank - b.rank;

Example: 例:

 var arr = [{ name: "Apple", rank: 25 }, { name: "Cherry", rank: 29 }, { name: "Grape", rank: 15 }]; arr.sort(function(a, b) { return a.rank - b.rank; }); console.log(arr); 

Note: To reverse the order of the sorting, do this instead: 注意:要颠倒排序顺序,请执行以下操作:

return b.rank - a.rank;

One way you can solve this problem is using Quick Sort algorithm. 解决此问题的一种方法是使用快速排序算法。 Below I've implemented the algorithm which will print to the console your array before sort, and array after sort. 下面,我实现了该算法,该算法将在排序之前将数组打印到控制台,在排序之后将数组打印到控制台。

  var a = [ { name: "Apple", rank: 25 }, { name: "Cherry", rank: 29 }, { name: "Grape", rank: 15 } ]; console.log(a); function swap(firstIndex, secondIndex){ var temp = a[firstIndex]; a[firstIndex] = a[secondIndex]; a[secondIndex] = temp; } function partition(left, right) { var pivot = a[Math.floor((right + left) / 2)].rank, i = left, j = right; while (i <= j) { while (parseInt(a[i].rank) < pivot) { i++; } while (parseInt(a[j].rank) > pivot) { j--; } if (i <= j) { swap(i, j); i++; j--; } } return i; } function quickSort(left, right) { var index; if (a.length > 1) { left = typeof left != "number" ? 0 : left; right = typeof right != "number" ? a.length - 1 : right; index = partition(left, right); if (left < index - 1) { quickSort(left, index - 1); } if (index < right) { quickSort(index, right); } } } quickSort(a); console.log(a); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM