首页 > 解决方案 > 对可能包含 JavaScript 中未定义的数组进行排序

问题描述

我有一个要排序的字符串数组。该数组可能包含一些未定义的值。在这些情况下,对于升序,值应该在最后,而在降序中,值应该在开始。

我试过了

var content = ["Anuja", undefined, "Ranbir", "undefined"];

content.sort(function(a, b) {
  if (a == undefined) {
    a = ""
  }
  if (b == undefined) {
    b = ""
  }
  return a.localeCompare(b);
});

console.log(content)

使用此代码,我得到 ["","", "Anuja", "Ranbir"] 但我的要求是 ["Anuja", "Ranbir", "", ""]。

标签: javascriptsorting

解决方案


这不是微不足道的,但我找到了一种方法

let content = ["Anuja", null, "Ranbir", ,null]; // note the undefined entry at index 3

// one of the few ways to detect undefined entries
// .map IGNORES undefined entries
for (let i=0;i<content.length;i++) {
  content[i] = content[i] || ""; // you may want to test for 0 here
}

const asc = (a, b) => {
  if (a === "") return 1; // can be DRY'd using *dir where dir is -1 or 1
  if (b === "") return -1;
  return a.localeCompare(b);
};
const dsc = (a, b) => {
  if (a === "") return -1;
  if (b === "") return 1;
  return b.localeCompare(a);
}


content.sort(asc);
console.log(content)
content.sort(dsc);
console.log(content)


推荐阅读