javascript - jquery排序中如何让空数据排在最后

标签 javascript jquery json sorting

var data = [{
  "id": "2"
}, {
  "id": "3"
}, {
  "id": "4"
}, {
  "id": "5"
}, {
  "id": "6"
}, {
  "id": "7"
}, {
  "id": "1"
}, {
  "id": ""
}, {
  "id": ""
}, {
  "id": ""
}]

$('.up').click(function() {
  var prop = $(this).closest('th').attr('data-name');
  var data1 = sortResults(data, prop, 'asc')
  console.log(data1)
})
$('.down').click(function() {
  var prop = $(this).closest('th').attr('data-name');
  var data1 = sortResults(data, prop, 'desc')
  console.log(data1)
})


function sortResults(data, prop, asc) {
  console.log("done data " + data)
  console.log("done prop " + prop)
  console.log("done asc " + asc)
  data = data.sort(function(a, b) {
    if (asc)
      return (a[prop] > b[prop]);
    else
      return (b[prop] > a[prop]);
  });
  
  return data;
}
.up {
  display: block;
  height: 10px;
  width: 15px;
  background-repeat: no-repeat;
  background-color: blue;
  cursor: pointer;
}
.down {
  display: block;
  height: 10px;
  width: 15px;
  background-repeat: no-repeat;
  background-color: red;
  cursor: pointer;
}
.filter {
  display: inline-block;
  height: 14px;
  width: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
  <tr>
    <th data-name='id'>ID <span class='filter'><span class='up'></span><span class='down'></span></span>
    </th>
  </tr>
</table>

  1. 如何使具有空值的 id 位于 .sort() 的最后

最佳答案

您的sort回调不正确。如果第一项在第二项之前,则需要返回负数;如果第二项在第一项之前,则需要返回正数;如果它们“相同”,则需要返回 0。相反,您的函数返回 bool 值,它将被强制为 1(如果为 true)或 0(如果为 false),这将无法正确排序。

String#localeCompare 对于字符串排序很方便。不过,它会认为""比任何内容都“更早”,所以我们必须特殊情况:

function sortResults(data, prop, asc) {
  data.sort(function(a, b) {
    var vala = a[prop],
        valb = b[prop];
    if (!vala) {
        // vala is blank -- if valb is also blank, return 0;
        // otherwise, return 1 to put vala *after* valb
        return !valb ? 0 : 1;
    }
    if (!valb) {
        // valb is blank, return -1 to put it *after* vala
        return -1;
    }
    if (asc) {
      // Ascending sort, use localeCompare
      return vala.localeCompare(valb);
    }
    // Descending sort, use localeCompare the other way around
    return valb.localeCompare(vala);
  });

  return data;
}
<小时/>

旁注:Array#sort 对数组进行就地排序,因此不需要 data = data.sort(...) .

关于javascript - jquery排序中如何让空数据排在最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717154/

相关文章:

javascript - jQuery UI 错误 - f.getClientRects 不是函数

javascript - 在 Vuejs 中覆盖导入的 CSS 样式

javascript - 正则表达式/[a-zA-Z0-9_-]/传 `!!!`时返回true

javascript - Rails3-jquery-autocomplete 没有响应

ios - 将保存的上下文从 AppDelegate 加载到另一个 ViewController

json - 如何使用curl使用JSON数据进行POST调用?

json - 如何使用 ng-repeat 显示来自 json 的数据

javascript - 但是 var 不是针对局部变量的吗?

javascript - 如何在ajax请求中将进度条停止在100%?

jquery - Stylus 中的 CSS3 转换 - 如何针对 IE9 降级