Json排序不起作用

时间:2017-12-30 15:16:52

标签: javascript json google-cloud-functions

我的json看起来像这样:

[
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
]

我试图通过用户现金对json进行排序。 所以我做的是:

    var objArr = []; // the json array

    function compare(a, b) {
        console.log("a" + a.cash);
        console.log("b" + b.cash);
        if (a.cash > b.cash)
            return -1;
        if (a.cash < b.cash)
            return 1;
        return 0;
    }

   var obj = objArr.sort(compare);
   response.send(obj);

但是没有订购回复的回复。

我该如何解决? 感谢

2 个答案:

答案 0 :(得分:1)

A couple of notes:

  1. Your code is sorting in descending order (it's not unordered).

  2. Your code is using the return value of sort. Just beware that that gives the misleading impression that the returned array is not the same array as the original. It is the same array, so generally best not to use the return value.

  3. Your sort can be much shorter:

    // Ascending:
    return a.cash - bcash;
    
    // Or descending:
    return b.cash - a.cash;
    

Proof of #1 above:

var objArr = [
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
];

function compare(a, b) {
  console.log("a" + a.cash);
  console.log("b" + b.cash);
  if (a.cash > b.cash)
    return -1;
  if (a.cash < b.cash)
    return 1;
  return 0;
}

var obj = objArr.sort(compare);
console.log(obj);
.as-console-wrapper {
  max-height: 100% !important;
}

Demo of #2 and #3:

var objArr = [
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
];

console.log("ascending", objArr.sort((a, b) => a.cash - b.cash));
console.log("descending", objArr.sort((a, b) => b.cash - a.cash))
.as-console-wrapper {
  max-height: 100% !important;
}

答案 1 :(得分:0)

尝试以下方法:

var arr = [
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
]

var res = arr.sort(function(a, b){
    // ascending
    return a.cash - b.cash;
    // descending
    // return b.cash - a.cash;
});

console.log(res);