我有一个数组,需要对其进行排序,就像在Oracle SQl中使用 order by 一样. 如果我有以下数组:
I have an Array that I need to sort exactly like using order by in Oracle SQl. If I have following Array:
var array = ['Ba12nes','Apfel','Banane','banane','abc','ABC','123','2', null,'ba998ne'] var.sort(compare);我希望得到以下结果
var array = ['abc','ABC','Apfel','banane','Banane','Ba12nes','ba998ne','123','2', null]如果null值在其他位置,则我没有任何问题.
If the null values are somewhere else, I don't have a Problem with it.
我当前的解决方案,对我没有帮助^^
My current solution, which does not help me ^^
function compare(a,b) { if(a == null) return -1; if (b == null) return 1; if (a.toLowerCase() < b.toLowerCase()) return -1; if (a.toLowerCase() > b.toLowerCase()) return 1; return 0; }我确实知道我需要自定义排序功能.目前,我认为只有正则表达式才能解决对数字前面的字符串值进行排序的问题.但是我仍然不确定如何用小写字母代替大写字母来解决问题.
I do understand that i need a custom sorting function. And at the moment I am thinking that only a regular expression can solve the problem of sorting the string values in front of the numbers. But I am still not sure how to solve the Problem with lowercase letters in bevor Uppercase letters.
推荐答案此提案无需使用Intl.Collator即可进行排序.第一种解决方案是直接排序并比较给定值.
This proposals feature sorting without use of Intl.Collator. The first solution works with direct sort and comparing the given values.
var array = ['Ba12nes', 'Apfel', 'Banane', 'banane', 'abc', 'ABC', '123', '2', null, 'ba998ne']; array.sort(function (a, b) { var i = 0; if (a === null && b === null) { return 0; } if (a === null) { return 1; } if (b === null) { return -1; } while (i < a.length && i < b.length && a[i].toLocaleLowerCase() === b[i].toLocaleLowerCase()) { i++; } if (isFinite(a[i]) && isFinite(b[i])) { return a[i] - b[i]; } if (isFinite(a[i])) { return 1; } if (isFinite(b[i])) { return -1; } return a.localeCompare(b); }); document.write(JSON.stringify(array));
第二个解决方案基于使用地图排序和采用新字符串的自定义排序方案.字符串是根据以下规则构建的:
The second solution features a different approach, based on Sorting with map and a custom sort scheme which takes a new string. The string is build by this rules:
新的构建字符串与a.value.localeCompare(b.value)一起使用.
The new build string is used with a a.value.localeCompare(b.value).
以下是具有映射值的字符串:
Here are the strings with the mapped values:
' B a 1 2 n e s' ' A p f e l' ' B a n a n e' ' b a n a n e' ' a b c' ' A B C' ' 1 2 3 ' ' 2 ' 'null' ' b a 9 9 8 n e'经过分类,就变成了
' a b c' ' A B C' ' A p f e l' ' b a n a n e' ' B a n a n e' ' B a 1 2 n e s' ' b a 9 9 8 n e' ' 1 2 3 ' ' 2 ' 'null'var array = ['Ba12nes', 'Apfel', 'Banane', 'banane', 'abc', 'ABC', '123', '2', null, 'ba998ne'], mapped = array.map(function (el, i) { var j, o = { index: i, value: '' }; if (el === null) { o.value = 'null'; return o; } for (j = 0; j < el.length; j++) { o.value += /\d/.test(el[j]) ? ' ' + el[j] + ' ' : ' ' + el[j]; } return o; }); mapped.sort(function (a, b) { return a.value.localeCompare(b.value); }); var result = mapped.map(function (el) { return array[el.index]; }); document.write(JSON.stringify(result));
更多推荐
Javascript在Oracle中按顺序对数组进行排序
发布评论