I have a problem with sorting arrays in javascript:
My original array:
let orginalArray = ["Apple","apple","Acrobat","Account","account","Banana","banana","carrot","Carrot",1,2];
Looking for an output like this:
sortedArray = ["Account","Acrobat","Apple","account","apple","Banana","banana","Carrot","carrot",1,2];
This is what I tried:
let sortedArray = orginalArray;
sortedArray.sort((a, b) => a[keyname].toString().localeCompare(b[keyname].toString(),'en', { caseFirst: 'upper' }));
expecting,
sortedArray = ["Account","Acrobat","Apple","account","apple","Banana","banana","Carrot","carrot",1,2];
2
Answers
Some crazy almost one-liner could be the following.
The trick is
a[0]?.localeCompare(b[0],'en', { caseFirst: 'upper' })
which returnsundefined
ifa
is a number or-1
ifb
is a number or a string which sorted accordingly.The following snippet will