【问题标题】:Sorting by Alphabetic, then Symbols in NodeJS按字母顺序排序,然后是 NodeJS 中的符号
【发布时间】:2021-09-05 02:44:16
【问题描述】:

按字母排序的最佳方法是什么,然后是 javascript/node 中的符号?我在下面使用此函数按字母顺序对其进行排序,但是“_text”在顶部排序。

const items = {
"objectb": "text",
"objecta": "one",
"_text": "two",
"objectc": "three"
}

const ordered = Object.keys(items).sort().reduce(
        (obj, key) => {
            obj[key] = items[key];
            return obj;
        }, {}
    );

// This produces the sorted object, however the symbol key is sorted at the top, whereas I would like it at the bottom.

RETURNS:
{
"_text": "text",
"objecta": "one",
"objectb": "two",
"objectc": "three"
}

WOULD LIKE:
{
"objecta": "one",
"objectb": "two",
"objectc": "three",
"_text": "text"
}

【问题讨论】:

  • 将您自己的排序函数作为参数传递给sort
  • 如果您关心订单,请不要使用对象。

标签: javascript node.js sorting


【解决方案1】:

你可以先把字符串分成两个数组,分别排序,然后合并。如果存在任何其他符号,这将起作用。

const items = {
  objectb: "text",
  objecta: "one",
  _text: "two",
  objectc: "three",
};

const strComparator = (a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
};

const ordered = Object.keys(items).reduce(
    (acc, curr) => {
      if (/[a-z]/i.test(curr[0])) acc[0].push(curr);
      else acc[1].push(curr);
      return acc;
    },[[], []])
  .flatMap((arr) => arr.sort(strComparator))
  .reduce((obj, key) => {
    obj[key] = items[key];
    return obj;
  }, {});

console.log(ordered);

【讨论】:

    【解决方案2】:

    需要提供排序功能

    var array = ['_', 'a', 'b']
    
    array.sort(function(a, b) {
      // sort _ at the end
      if (a[0] == '_' && b[0] != '_') return 1;
      if (a[0] != '_' && b[0] == '_') return -1;
      // sort by standard string comparison
      return a.localeCompare(b);
    })
    

    【讨论】:

    • localeCompare 不是标准的字符串比较
    • 问题是“按字母排序,然后按符号排序的最佳方法是什么”?第一个位置的下划线显然只是一个例子。
    • 我的错,可能是英语语言问题,因为我不是以英语为母语的人。我的意思是与“默认”相对的标准。确实它不是默认使用的一种。
    • 那它回答问题了吗?stackoverflow.com/questions/10951167/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2022-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多