Question:
For example, there is an array:
arr = ['б', 'D', 7, 'U', 'Ш', 9, 5, 'J']
And I need to sort it alphabetically, and bring it to this:
sort === ['D', 'J', 'U', 'б', 'Ш', 5, 7, 9];
I do this, but the Cyrillic alphabet and numbers are thrown forward:
let sort = arr.sort(function (a, b) {
return a._id.toLowerCase().localeCompare(b._id.toLowerCase())
});
Answer:
to compare letters depending on the language, you can use Intl.Collator
indicating the desired locale, in this case en
, so that Latin letters come before Cyrillic. But the numbers will still be the first, so you need to check the options at each iteration when one of the arguments is a number and the second is not
- when
a
is NOT a number andb
is a number we return -1 so that the values are not swapped - when
a
is a number andb
is NOT a number, return 1 so that the letter comes before the number - in other cases, when both parameters are a number or both are NOT a number, we use
collator
to sort letters and numbers among themselves
Intl.Collator also has the Intl.Collator
caseFirst
, which specifies which case characters should come first
const arr = ['б', 'D', 7, 'U', 'Ш', 9, 5, 'J']
const collator = new Intl.Collator('en');
const sortArr = arr.sort((a, b) => {
if(isNaN(a) && !isNaN(b)){
return -1
}else if(!isNaN(a) && isNaN(b)){
return 1
}
return collator.compare(a, b);
});
console.log(sortArr);