Dan*_*ana 3 javascript arrays sorting object
我有一个像这样的对象数组
array[0] = {id: 1, name: "First"}
array[1] = {id: 2, name: "Second"}
Run Code Online (Sandbox Code Playgroud)
我尝试name使用以下方法按字段排序:
Array.prototype.alphanumSort = function (caseInsensitive) {
for (var z = 0, t; t = ((typeof this[z] == "string" || typeof this[z] == "undefined") ? this[z] : this[z].name); z++) {
this[z] = new Array();
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >= 48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function (a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
Run Code Online (Sandbox Code Playgroud)
但我从中返回的列表包含一个数组,其中仅包含name其中的字段,而没有相应的id. 为什么会发生这种情况?有没有办法应用这个算法来过滤对象?我是 JavaScript 新手,所以请保持温柔。
您可以使用map和String#localeComparewith进行排序options
\n\n灵敏度
\n字符串中的哪些差异应导致非零结果值。可能的值为:
\n\n
\n- \n
"base":只有基本字母不同的字符串才比较为不相等。例子:a \xe2\x89\xa0 b,a = \xc3\xa1,a = A。- \n
"accent":只有基本字母或重音符号以及其他变音符号不同的字符串才会被视为不相等。例子:a \xe2\x89\xa0 b,a \xe2\x89\xa0 \xc3\xa1,a = A。- \n
"case":只有基本字母或大小写不同的字符串才比较为不相等。例子:a \xe2\x89\xa0 b,a = \xc3\xa1,a \xe2\x89\xa0 A。- \n
"variant":基本字母、重音符号和其他变音符号不同或大小写不同的字符串比较为不相等。还可以考虑其他差异。例子:a \xe2\x89\xa0 b,a \xe2\x89\xa0 \xc3\xa1,a \xe2\x89\xa0 A。默认为“variant”,用于“sort”用法;它的使用“搜索”取决于区域设置。
\n数字
\n是否应使用数字排序规则,例如“1”<“2”<“10”。可能的值为
\ntrue和false;默认为false. 该选项可以通过选项属性或通过 Unicode 扩展键来设置;如果两者都提供,则options属性优先。不需要实现来支持此属性。
var array = [\'Ex 10\', \'Ex 2\', \'a 10.1\', \'a 1.1\', \'a 10.0\', \'a 2.0\'];\n\narray.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: \'base\' }));\n\nconsole.log(array)Run Code Online (Sandbox Code Playgroud)\r\n| 归档时间: |
|
| 查看次数: |
4030 次 |
| 最近记录: |