I'm trying to sort an array by keys with swedish chars in an alphabetical "Natural sort order". This is the test array:
var test = [];
test["abc"] = [];
test["ABC"] = [];
test["test"] = [];
test["Test"] = [];
test["åäö"] = [];
test["ÅÄÖ"] = [];
The desired result is the order the array is created (abc, ABC, test, Test, åäö, ÅÄÖ), but I can't figure out how to get that order.
I've tried using:
var sortedKeys = Object.keys(test).sort();
And:
var sortedKeys= Object.keys(test).sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
But I can't get the desired order of the keys. Here's a jsfiddle with some tests: https://jsfiddle.net/3cs491gq/
Thanks for any help sorting (!) this out.
Don't use toLowerCase
, and just use sort
with localeCompare
:
var test = []; test["ÅÄÖ"] = []; test["abc"] = []; test["ABC"] = []; test["test"] = []; test["Test"] = []; test["åäö"] = []; var sortedKeys = Object.keys(test).sort((a, b) => !/[az]/i.test(a) ? 1 : (/[az]/i.test(b) ? 0 : -1)); console.log(sortedKeys);
Well your code seems to work. You should not use toLowerCase
though.
Here i made a test for you.
var test = []; test["ÅÄÖ"] = []; test["abc"] = []; test["ABC"] = []; test["test"] = []; test["Test"] = []; test["åäö"] = []; var data =Object.keys(test).sort(function(a,b){ return a.localeCompare(b); }); console.log(data);
You can simply add the proper parameters to localeCompare like so:
var test = []; test["ÅÄÖ"] = []; test["abc"] = []; test["ABC"] = []; test["test"] = []; test["Test"] = []; test["åäö"] = []; var r = Object.keys(test).sort((a, b) => a.localeCompare(b, "sv", {sensitivity: 'case'})); console.log(r);
In this case we add sv
for the Swedish
locale and sensitivity: 'case'
as the option.
I finally found a way that seems to work quite well, at least in new versions of Chrome, Safari and Opera. This question was very helpful: How to sort special letters (typescript)?
var test = [];
test["abc"] = [];
test["ABC"] = [];
test["test"] = [];
test["Test"] = [];
test["åäö"] = [];
test["ÅÄÖ"] = [];
var sortedKeys = Object.keys(test).sort(new Intl.Collator("sv", { usage: "sort" }).compare);
console.log(sortedKeys);
There's a jsfiddle here: https://jsfiddle.net/ryv4hjk5/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.