按字母排序,然后在NodeJS中按符号排序



按字母排序,然后按javascript/node中的符号排序的最佳方式是什么?我在下面使用了这个函数来按字母顺序对其进行排序_文本";排序在顶部。

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"
}

您可以先将字符串分隔成两个数组,然后分别对它们进行排序,然后将它们组合。如果存在任何其他符号,这将起作用。

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);

您需要提供一个排序功能

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);
})

最新更新