Javascript 根据排序期间的条件将项目放置在底部

Javascript 根据排序期间的条件将项目放置在底部,javascript,Javascript,我有一个目标: [ {'id': 3, 'count': 9}, {'id': 4,'count': null}, {'id':5,'count':4}] 基本上,顺序应该是count,但如果count为null,则应将项目放在排序的底部。我尝试了以下方法,但不起作用。上述内容应给出(对于asc): 下降时: {'id': 5, 'count': 4} {'id':3,'count':9} {'id': 4,'count': null} 代码 let sortValue =

我有一个目标:

  [ {'id': 3, 'count': 9}, {'id': 4,'count': null}, {'id':5,'count':4}]
基本上,顺序应该是count,但如果count为null,则应将项目放在排序的底部。我尝试了以下方法,但不起作用。上述内容应给出(对于asc):

下降时:

  {'id': 5, 'count': 4}
  {'id':3,'count':9}
  {'id': 4,'count': null}
代码

let sortValue = -1; //asc
let direction = 'asc';

if (direction != "asc") {
  sortValue = 1;
}

objArr.sort(function(a: Item, b: Item) {

      const aCount  = a['count'] ;
      const bCount  = b['count'];

      if ( aCount == null){
        return -1;
      }

      if ( bCount == null){
        return -1;
      }

      return aCount>bCount? -1 * sortValue : aCount<bCount ? sortValue : 0;
让sortValue=-1//asc
let direction='asc';
如果(方向!=“asc”){
sortValue=1;
}
对象排序(函数(a:项,b:项){
常量a计=a['count'];
常量bCount=b['count'];
if(aCount==null){
返回-1;
}
if(bCount==null){
返回-1;
}

返回aCount>bCount?-1*sortValue:aCount您可以检查
null
并将检查结果作为排序顺序

函数排序(数组,顺序='asc'){
变量系数=顺序=='desc'| |-1;
返回array.sort({count:a},{count:b})=>
(a===null)-(b===null)| |//将null移到底部
因子*(a-b)//按数值排序
);
}
var数组=[{id:3,count:9},{id:4,count:null},{id:5,count:4}];
log(排序(数组));

console.log(sort(array,'desc'));
您需要定义返回值
-1
0
1
的所有情况,以便
.sort()
正常工作:

let direction = 'asc';

objArr.sort((a, b) => {

  if (a.count === null && b.count === null) {
    return 0;
  }

  if (a.count === null) {
    return 1;
  }

  if (b.count=== null) {
    return -1;
  }

  // Ascending direction
  if (direction === 'asc') {
    return a.count - b.count;
  }

  // Descending direction
  return b.count - a.count;
}

如果始终希望
null
值位于底部,则当
a
为null时返回
1
,当
b
为null时返回
-1

函数排序(数组,排序值){
返回array.sort(函数({count:a},{count:b}){
如果(a==null)返回1;
if(b==null)返回-1;
返回值(b-a)*sortValue;
});
}
var数组=[{id:3,count:9},{id:4,count:null},{id:5,count:4}];
log(排序(数组,-1));

console.log(排序(数组,1))
无论哪个数字为空,都返回
-1
?嘿@Bravo这就是我理解的将它们推到底的方法。但是基本上,如果计数为空,则项目应该在底部。基本上,所有计数为空的项目都应该放在列表的底部。我假设返回-1会将项目推到底在下面的列表中,我想我错了。你给这个问题添加了javascript标签,但是你粘贴的代码看起来像是TypeScript。请添加asc和desc的排序结果。在这种情况下,
null
应该去哪里?我想,不管aCount或bCount是否为null,你都返回-1的事实破坏了排序。该算法如何处理如果函数返回相同的值,不管null是第一个值还是第二个值,则将null移到底部?即使在
desc
@Nina Scholz:对asc有效,但不适用于Jamiec所说的desc。仍然要感谢。这将导致
9,4,null
null,9,4
-始终描述nding,null结束于top@NieSelam,为什么需要排序顺序?这会发生什么?两个空项同时出现是什么情况?@NinaScholz这有关系吗?它们都将放在底部,我认为两个空值的顺序并不重要
let direction = 'asc';

objArr.sort((a, b) => {

  if (a.count === null && b.count === null) {
    return 0;
  }

  if (a.count === null) {
    return 1;
  }

  if (b.count=== null) {
    return -1;
  }

  // Ascending direction
  if (direction === 'asc') {
    return a.count - b.count;
  }

  // Descending direction
  return b.count - a.count;
}