排序功能有什么问题,也需要改进

时间:2014-05-21 12:34:06

标签: javascript performance logic

我有一个json对象有一些记录,我需要对对象进行排序,

代码:

var data = [
{
  "MRData": {        
    "StandingsTable": {
      "StandingsLists": [
        {
          "season": "2014",
          "round": "5",
          "DriverStandings": [
            {
              "position": "2",
              "positionText": "1",
              "points": "100",
              "wins": "4",
              "Driver": {...},
              "Constructors": [...]
            },
            {
              "position": "1",
              "positionText": "2",
              "points": "97",
              "wins": "1",
              "Driver": {...},
              "Constructors": [...]
            }
          ]
        }
      ]
    }
  }
}
];

//此功能中的错误

function sortObj(obj, nextObj){
    console.log(obj.position);
    console.log(nextObj.position);
    if(obj.position < nextObj.position){
        return obj;
    }else{
        return nextObj;
    }
}

var driverObjects = data[0].MRData.StandingsTable.StandingsLists[0].DriverStandings;
console.log(driverObjects);
var sortedData = driverObjects.sort(sortObj); //Do I need to use any other functions //like filter, map ?
console.log(sortedData);
  

Fiddle

看一下控制台,使用输出,我除了输出

[Object {position =&#34; 1&#34;,positionText =&#34; 1&#34 ;, points =&#34; 100&#34;,more ...},Object {position =& #34; 2&#34;,positionText =&#34; 2&#34;,points =&#34; 97&#34;,more ...}]

但它与传递的功能显示相同。

  1. 请更正功能错误。
  2. 为我提供优化或更标准的代码实现

2 个答案:

答案 0 :(得分:1)

sortObj()应返回值或否定值或 0

你可以这样做..

function sortObj(obj, nextObj){
    console.log(obj.position);
    console.log(nextObj.position);
    return nextObj.position-obj.position
}

答案 1 :(得分:0)

sort方法的回调函数应该返回-1(当第二个参数更大时),0(当两个参数相等时)或1(当第一个参数是更大)的

Array.prototype.sort()

所以你需要这个排序功能:

function sortObj(obj, nextObj){
    return obj.position - nextObj.position;
}