Sort mixed alpha/numeric array
I have a mixed array that I need to sort by alphabet and then by digit
[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3]
How do I sort it to be:
[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12]
I have tried
arr.sort(function(a,b) {return a - b});
but that only sorts it alphabetically.
Can this be done with either straight JavaScript or jQuery?
javascript jquery arrays sorting
add a comment |
I have a mixed array that I need to sort by alphabet and then by digit
[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3]
How do I sort it to be:
[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12]
I have tried
arr.sort(function(a,b) {return a - b});
but that only sorts it alphabetically.
Can this be done with either straight JavaScript or jQuery?
javascript jquery arrays sorting
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
1
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35
add a comment |
I have a mixed array that I need to sort by alphabet and then by digit
[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3]
How do I sort it to be:
[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12]
I have tried
arr.sort(function(a,b) {return a - b});
but that only sorts it alphabetically.
Can this be done with either straight JavaScript or jQuery?
javascript jquery arrays sorting
I have a mixed array that I need to sort by alphabet and then by digit
[A1, A10, A11, A12, A2, A3, A4, B10, B2, F1, F12, F3]
How do I sort it to be:
[A1, A2, A3, A4, A10, A11, A12, B2, B10, F1, F3, F12]
I have tried
arr.sort(function(a,b) {return a - b});
but that only sorts it alphabetically.
Can this be done with either straight JavaScript or jQuery?
javascript jquery arrays sorting
javascript jquery arrays sorting
edited Jan 29 at 14:53
Mel
3,76892430
3,76892430
asked Dec 2 '10 at 21:38
solefaldsolefald
6841825
6841825
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
1
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35
add a comment |
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
1
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
1
1
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35
add a comment |
13 Answers
13
active
oldest
votes
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of^
and$
front and back respectively on each.
– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
So catching up a little late...but you don't need theelse
block since the firstif
willreturn
ifaA === bA
– phatskat
Jan 20 '14 at 16:40
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
|
show 9 more comments
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`
Usage:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
Gives:
["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]
You may have to change the 'en'
argument to your locale or determine programatically but this works for english strings.
Also localeCompare
isn't super consistently supported but if your transpiling with babel that won't be a problem
add a comment |
I had a similar situation, but, had a mix of alphanumeric & numeric and needed to sort all numeric first followed by alphanumeric, so:
A10
1
5
A9
2
B3
A2
needed to become:
1
2
5
A2
A9
A10
B3
I was able to use the supplied algorithm and hack a bit more onto it to accomplish this:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return -1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return 1 here
}else{
return AInt > BInt ? 1 : -1;
}
}
var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);
1
["a25b", "ab", "a37b"]
will produces[ "a25b", "ab", "a37b" ]
instead of[ "a25b", "a37b", "ab" ]
.
– 林果皞
Dec 21 '17 at 20:07
add a comment |
This could do it:
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
add a comment |
var a1 =["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"];
var a2 = a1.sort(function(a,b){
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];
if(charPart[0] < charPart[1]) return -1;
else if(charPart[0] > charPart[1]) return 1;
else{ //(charPart[0] == charPart[1]){
if(numPart[0] < numPart[1]) return -1;
else if(numPart[0] > numPart[1]) return 1;
return 0;
}
});
$('#r').html(a2.toString())
http://jsfiddle.net/8fRsD/
add a comment |
Only problem with the above given solution was that the logic failed when numeric data was same & alphabets varied e.g. 28AB, 28PQR, 28HBC.
Here is the modified code.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
alert("in if "+aN+" : "+bN);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return 1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return -1 here
}else if(AInt == BInt) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
return aA > bA ? 1 : -1;
}
else {
return AInt > BInt ? 1 : -1;
}
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
add a comment |
Adding to the accepted answer from epascarello, since I cannot comment on it. I'm still a noob here.
When one of the strinngs doesn't have a number the original answer will not work. For example A and A10 will not be sorted in that order. Hence you might wamnt to jump back to normal sort in that case.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
if(isNaN(bN) || isNaN(bN)){
return a > b ? 1 : -1;
}
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12","F3"].sort(sortAlphaNum);`
add a comment |
I have solved the above sorting problem with below script
arrVals.sort(function(a, b){
//return b.text - a.text;
var AInt = parseInt(a.text, 10);
var BInt = parseInt(b.text, 10);
if ($.isNumeric(a.text) == false && $.isNumeric(b.text) == false) {
var aA = a.text
var bA = b.text;
return aA > bA ? 1 : -1;
} else if ($.isNumeric(a.text) == false) { // A is not an Int
return 1; // to make alphanumeric sort first return -1 here
} else if ($.isNumeric(b.text) == false) { // B is not an Int
return -1; // to make alphanumeric sort first return 1 here
} else {
return AInt < BInt ? 1 : -1;
}
});
This works fine for a well mixed array.:)
Thank you.
add a comment |
alphaNumericCompare(a, b) {
let ax = , bx = ;
a.replace(/(d+)|(D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || '']) });
b.replace(/(d+)|(D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || '']) });
while (ax.length && bx.length) {
let an = ax.shift();
let bn = bx.shift();
let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
}
add a comment |
Here is an ES6 Typescript upgrade to this answer.
export function SortAlphaNum(a: string, b: string) {
const reA = /[^a-zA-Z]/g;
const reN = /[^0-9]/g;
const aA = a.replace(reA, "");
const bA = b.replace(reA, "");
if (aA === bA) {
const aN = parseInt(a.replace(reN, ""), 10);
const bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
add a comment |
A simple way to do this is use the localeCompare() method of JavaScript
https://www.w3schools.com/jsref/jsref_localecompare.asp
Example:
export const sortAlphaNumeric = (a, b) => {
// convert to strings and force lowercase
a = typeof a === 'string' ? a.toLowerCase() : a.toString();
b = typeof b === 'string' ? b.toLowerCase() : b.toString();
return a.localeCompare(b);
};
Expected behavior:
1000X Radonius Maximus
10X Radonius
200X Radonius
20X Radonius
20X Radonius Prime
30X Radonius
40X Radonius
Allegia 50 Clasteron
Allegia 500 Clasteron
Allegia 50B Clasteron
Allegia 51 Clasteron
Allegia 6R Clasteron
Alpha 100
Alpha 2
Alpha 200
Alpha 2A
Alpha 2A-8000
Alpha 2A-900
Callisto Morphamax
Callisto Morphamax 500
Callisto Morphamax 5000
Callisto Morphamax 600
Callisto Morphamax 6000 SE
Callisto Morphamax 6000 SE2
Callisto Morphamax 700
Callisto Morphamax 7000
Xiph Xlater 10000
Xiph Xlater 2000
Xiph Xlater 300
Xiph Xlater 40
Xiph Xlater 5
Xiph Xlater 50
Xiph Xlater 500
Xiph Xlater 5000
Xiph Xlater 58
add a comment |
You can use Intl.Collator
It has performance benefits over localeCompare
Read here
Browser comparability ( All the browser supports it )
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
add a comment |
function sortAlphaNum(a, b) {
var smlla = a.toLowerCase();
var smllb = b.toLowerCase();
var result = smlla > smllb ? 1 : -1;
return result;
}
1
This is wrong. Try comparingA10
toA2
. This will sortA10
beforeA2
, butA2
should be sorted beforeA10
.
– cpburnz
Jul 14 '15 at 0:53
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4340227%2fsort-mixed-alpha-numeric-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of^
and$
front and back respectively on each.
– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
So catching up a little late...but you don't need theelse
block since the firstif
willreturn
ifaA === bA
– phatskat
Jan 20 '14 at 16:40
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
|
show 9 more comments
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of^
and$
front and back respectively on each.
– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
So catching up a little late...but you don't need theelse
block since the firstif
willreturn
ifaA === bA
– phatskat
Jan 20 '14 at 16:40
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
|
show 9 more comments
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)
edited Aug 28 '18 at 11:33
Luca Kiebel
7,35141531
7,35141531
answered Dec 2 '10 at 21:52
epascarelloepascarello
153k14133183
153k14133183
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of^
and$
front and back respectively on each.
– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
So catching up a little late...but you don't need theelse
block since the firstif
willreturn
ifaA === bA
– phatskat
Jan 20 '14 at 16:40
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
|
show 9 more comments
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of^
and$
front and back respectively on each.
– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
So catching up a little late...but you don't need theelse
block since the firstif
willreturn
ifaA === bA
– phatskat
Jan 20 '14 at 16:40
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of
^
and $
front and back respectively on each.– Orbling
Dec 2 '10 at 21:56
Just beat me too it, only modification I would suggest, given the ordering of the tests, the regexp should also be ordered via addition of
^
and $
front and back respectively on each.– Orbling
Dec 2 '10 at 21:56
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
Genius! Exactly what i needed. Thank you!!!
– solefald
Dec 2 '10 at 21:57
3
3
So catching up a little late...but you don't need the
else
block since the first if
will return
if aA === bA
– phatskat
Jan 20 '14 at 16:40
So catching up a little late...but you don't need the
else
block since the first if
will return
if aA === bA
– phatskat
Jan 20 '14 at 16:40
1
1
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
@Noitidart preference. There should be no difference between the two.
– epascarello
Dec 18 '15 at 14:37
3
3
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
This is a good answer but it very badly needs comments. It took me awhile to read this and for it to make sense.
– zfrisch
May 30 '17 at 21:16
|
show 9 more comments
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`
Usage:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
Gives:
["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]
You may have to change the 'en'
argument to your locale or determine programatically but this works for english strings.
Also localeCompare
isn't super consistently supported but if your transpiling with babel that won't be a problem
add a comment |
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`
Usage:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
Gives:
["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]
You may have to change the 'en'
argument to your locale or determine programatically but this works for english strings.
Also localeCompare
isn't super consistently supported but if your transpiling with babel that won't be a problem
add a comment |
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`
Usage:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
Gives:
["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]
You may have to change the 'en'
argument to your locale or determine programatically but this works for english strings.
Also localeCompare
isn't super consistently supported but if your transpiling with babel that won't be a problem
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })`
Usage:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
Gives:
["A1", "A2", "A3", "A4", "A10", "A11", "A12", "B2", "B10", "F1", "F3", "F12"]
You may have to change the 'en'
argument to your locale or determine programatically but this works for english strings.
Also localeCompare
isn't super consistently supported but if your transpiling with babel that won't be a problem
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true })
console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
edited Jan 29 at 14:53
Mel
3,76892430
3,76892430
answered May 26 '17 at 8:45
Jon WyattJon Wyatt
20425
20425
add a comment |
add a comment |
I had a similar situation, but, had a mix of alphanumeric & numeric and needed to sort all numeric first followed by alphanumeric, so:
A10
1
5
A9
2
B3
A2
needed to become:
1
2
5
A2
A9
A10
B3
I was able to use the supplied algorithm and hack a bit more onto it to accomplish this:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return -1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return 1 here
}else{
return AInt > BInt ? 1 : -1;
}
}
var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);
1
["a25b", "ab", "a37b"]
will produces[ "a25b", "ab", "a37b" ]
instead of[ "a25b", "a37b", "ab" ]
.
– 林果皞
Dec 21 '17 at 20:07
add a comment |
I had a similar situation, but, had a mix of alphanumeric & numeric and needed to sort all numeric first followed by alphanumeric, so:
A10
1
5
A9
2
B3
A2
needed to become:
1
2
5
A2
A9
A10
B3
I was able to use the supplied algorithm and hack a bit more onto it to accomplish this:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return -1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return 1 here
}else{
return AInt > BInt ? 1 : -1;
}
}
var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);
1
["a25b", "ab", "a37b"]
will produces[ "a25b", "ab", "a37b" ]
instead of[ "a25b", "a37b", "ab" ]
.
– 林果皞
Dec 21 '17 at 20:07
add a comment |
I had a similar situation, but, had a mix of alphanumeric & numeric and needed to sort all numeric first followed by alphanumeric, so:
A10
1
5
A9
2
B3
A2
needed to become:
1
2
5
A2
A9
A10
B3
I was able to use the supplied algorithm and hack a bit more onto it to accomplish this:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return -1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return 1 here
}else{
return AInt > BInt ? 1 : -1;
}
}
var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);
I had a similar situation, but, had a mix of alphanumeric & numeric and needed to sort all numeric first followed by alphanumeric, so:
A10
1
5
A9
2
B3
A2
needed to become:
1
2
5
A2
A9
A10
B3
I was able to use the supplied algorithm and hack a bit more onto it to accomplish this:
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return -1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return 1 here
}else{
return AInt > BInt ? 1 : -1;
}
}
var newlist = ["A1", 1, "A10", "A11", "A12", 5, 3, 10, 2, "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum);
answered Jul 14 '14 at 17:58
cmccullohcmcculloh
23.6k3486122
23.6k3486122
1
["a25b", "ab", "a37b"]
will produces[ "a25b", "ab", "a37b" ]
instead of[ "a25b", "a37b", "ab" ]
.
– 林果皞
Dec 21 '17 at 20:07
add a comment |
1
["a25b", "ab", "a37b"]
will produces[ "a25b", "ab", "a37b" ]
instead of[ "a25b", "a37b", "ab" ]
.
– 林果皞
Dec 21 '17 at 20:07
1
1
["a25b", "ab", "a37b"]
will produces [ "a25b", "ab", "a37b" ]
instead of [ "a25b", "a37b", "ab" ]
.– 林果皞
Dec 21 '17 at 20:07
["a25b", "ab", "a37b"]
will produces [ "a25b", "ab", "a37b" ]
instead of [ "a25b", "a37b", "ab" ]
.– 林果皞
Dec 21 '17 at 20:07
add a comment |
This could do it:
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
add a comment |
This could do it:
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
add a comment |
This could do it:
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
This could do it:
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
function parseItem (item) {
const [, stringPart = '', numberPart = 0] = /(^[a-zA-Z]*)(d*)$/.exec(item) || ;
return [stringPart, numberPart];
}
function sort (array) {
return array.sort((a, b) => {
const [stringA, numberA] = parseItem(a);
const [stringB, numberB] = parseItem(b);
const comparison = stringA.localeCompare(stringB);
return comparison === 0 ? Number(numberA) - Number(numberB) : comparison;
});
}
console.log(sort(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3']))
console.log(sort(['a25b', 'ab', 'a37b']))
edited Nov 23 '18 at 9:22
answered Dec 2 '10 at 22:02
JanJan
6,73512956
6,73512956
add a comment |
add a comment |
var a1 =["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"];
var a2 = a1.sort(function(a,b){
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];
if(charPart[0] < charPart[1]) return -1;
else if(charPart[0] > charPart[1]) return 1;
else{ //(charPart[0] == charPart[1]){
if(numPart[0] < numPart[1]) return -1;
else if(numPart[0] > numPart[1]) return 1;
return 0;
}
});
$('#r').html(a2.toString())
http://jsfiddle.net/8fRsD/
add a comment |
var a1 =["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"];
var a2 = a1.sort(function(a,b){
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];
if(charPart[0] < charPart[1]) return -1;
else if(charPart[0] > charPart[1]) return 1;
else{ //(charPart[0] == charPart[1]){
if(numPart[0] < numPart[1]) return -1;
else if(numPart[0] > numPart[1]) return 1;
return 0;
}
});
$('#r').html(a2.toString())
http://jsfiddle.net/8fRsD/
add a comment |
var a1 =["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"];
var a2 = a1.sort(function(a,b){
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];
if(charPart[0] < charPart[1]) return -1;
else if(charPart[0] > charPart[1]) return 1;
else{ //(charPart[0] == charPart[1]){
if(numPart[0] < numPart[1]) return -1;
else if(numPart[0] > numPart[1]) return 1;
return 0;
}
});
$('#r').html(a2.toString())
http://jsfiddle.net/8fRsD/
var a1 =["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"];
var a2 = a1.sort(function(a,b){
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];
if(charPart[0] < charPart[1]) return -1;
else if(charPart[0] > charPart[1]) return 1;
else{ //(charPart[0] == charPart[1]){
if(numPart[0] < numPart[1]) return -1;
else if(numPart[0] > numPart[1]) return 1;
return 0;
}
});
$('#r').html(a2.toString())
http://jsfiddle.net/8fRsD/
answered Dec 2 '10 at 21:56
Josiah RuddellJosiah Ruddell
25.4k75262
25.4k75262
add a comment |
add a comment |
Only problem with the above given solution was that the logic failed when numeric data was same & alphabets varied e.g. 28AB, 28PQR, 28HBC.
Here is the modified code.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
alert("in if "+aN+" : "+bN);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return 1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return -1 here
}else if(AInt == BInt) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
return aA > bA ? 1 : -1;
}
else {
return AInt > BInt ? 1 : -1;
}
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
add a comment |
Only problem with the above given solution was that the logic failed when numeric data was same & alphabets varied e.g. 28AB, 28PQR, 28HBC.
Here is the modified code.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
alert("in if "+aN+" : "+bN);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return 1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return -1 here
}else if(AInt == BInt) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
return aA > bA ? 1 : -1;
}
else {
return AInt > BInt ? 1 : -1;
}
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
add a comment |
Only problem with the above given solution was that the logic failed when numeric data was same & alphabets varied e.g. 28AB, 28PQR, 28HBC.
Here is the modified code.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
alert("in if "+aN+" : "+bN);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return 1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return -1 here
}else if(AInt == BInt) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
return aA > bA ? 1 : -1;
}
else {
return AInt > BInt ? 1 : -1;
}
Only problem with the above given solution was that the logic failed when numeric data was same & alphabets varied e.g. 28AB, 28PQR, 28HBC.
Here is the modified code.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var AInt = parseInt(a, 10);
var BInt = parseInt(b, 10);
if(isNaN(AInt) && isNaN(BInt)){
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
alert("in if "+aN+" : "+bN);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}else if(isNaN(AInt)){//A is not an Int
return 1;//to make alphanumeric sort first return 1 here
}else if(isNaN(BInt)){//B is not an Int
return -1;//to make alphanumeric sort first return -1 here
}else if(AInt == BInt) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
return aA > bA ? 1 : -1;
}
else {
return AInt > BInt ? 1 : -1;
}
answered Jun 2 '17 at 11:45
Jarna KantariaJarna Kantaria
211
211
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
add a comment |
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
best answer for considering all kinds of mixed values - thanks a lot! :)
– meistermuh
Apr 23 '18 at 13:35
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
Take the alert() out of the example and it works great :-)
– Drew
Aug 28 '18 at 22:47
add a comment |
Adding to the accepted answer from epascarello, since I cannot comment on it. I'm still a noob here.
When one of the strinngs doesn't have a number the original answer will not work. For example A and A10 will not be sorted in that order. Hence you might wamnt to jump back to normal sort in that case.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
if(isNaN(bN) || isNaN(bN)){
return a > b ? 1 : -1;
}
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12","F3"].sort(sortAlphaNum);`
add a comment |
Adding to the accepted answer from epascarello, since I cannot comment on it. I'm still a noob here.
When one of the strinngs doesn't have a number the original answer will not work. For example A and A10 will not be sorted in that order. Hence you might wamnt to jump back to normal sort in that case.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
if(isNaN(bN) || isNaN(bN)){
return a > b ? 1 : -1;
}
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12","F3"].sort(sortAlphaNum);`
add a comment |
Adding to the accepted answer from epascarello, since I cannot comment on it. I'm still a noob here.
When one of the strinngs doesn't have a number the original answer will not work. For example A and A10 will not be sorted in that order. Hence you might wamnt to jump back to normal sort in that case.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
if(isNaN(bN) || isNaN(bN)){
return a > b ? 1 : -1;
}
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12","F3"].sort(sortAlphaNum);`
Adding to the accepted answer from epascarello, since I cannot comment on it. I'm still a noob here.
When one of the strinngs doesn't have a number the original answer will not work. For example A and A10 will not be sorted in that order. Hence you might wamnt to jump back to normal sort in that case.
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a,b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if(aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
if(isNaN(bN) || isNaN(bN)){
return a > b ? 1 : -1;
}
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12","F3"].sort(sortAlphaNum);`
answered Oct 24 '16 at 18:33
SunnyPenguinSunnyPenguin
53111
53111
add a comment |
add a comment |
I have solved the above sorting problem with below script
arrVals.sort(function(a, b){
//return b.text - a.text;
var AInt = parseInt(a.text, 10);
var BInt = parseInt(b.text, 10);
if ($.isNumeric(a.text) == false && $.isNumeric(b.text) == false) {
var aA = a.text
var bA = b.text;
return aA > bA ? 1 : -1;
} else if ($.isNumeric(a.text) == false) { // A is not an Int
return 1; // to make alphanumeric sort first return -1 here
} else if ($.isNumeric(b.text) == false) { // B is not an Int
return -1; // to make alphanumeric sort first return 1 here
} else {
return AInt < BInt ? 1 : -1;
}
});
This works fine for a well mixed array.:)
Thank you.
add a comment |
I have solved the above sorting problem with below script
arrVals.sort(function(a, b){
//return b.text - a.text;
var AInt = parseInt(a.text, 10);
var BInt = parseInt(b.text, 10);
if ($.isNumeric(a.text) == false && $.isNumeric(b.text) == false) {
var aA = a.text
var bA = b.text;
return aA > bA ? 1 : -1;
} else if ($.isNumeric(a.text) == false) { // A is not an Int
return 1; // to make alphanumeric sort first return -1 here
} else if ($.isNumeric(b.text) == false) { // B is not an Int
return -1; // to make alphanumeric sort first return 1 here
} else {
return AInt < BInt ? 1 : -1;
}
});
This works fine for a well mixed array.:)
Thank you.
add a comment |
I have solved the above sorting problem with below script
arrVals.sort(function(a, b){
//return b.text - a.text;
var AInt = parseInt(a.text, 10);
var BInt = parseInt(b.text, 10);
if ($.isNumeric(a.text) == false && $.isNumeric(b.text) == false) {
var aA = a.text
var bA = b.text;
return aA > bA ? 1 : -1;
} else if ($.isNumeric(a.text) == false) { // A is not an Int
return 1; // to make alphanumeric sort first return -1 here
} else if ($.isNumeric(b.text) == false) { // B is not an Int
return -1; // to make alphanumeric sort first return 1 here
} else {
return AInt < BInt ? 1 : -1;
}
});
This works fine for a well mixed array.:)
Thank you.
I have solved the above sorting problem with below script
arrVals.sort(function(a, b){
//return b.text - a.text;
var AInt = parseInt(a.text, 10);
var BInt = parseInt(b.text, 10);
if ($.isNumeric(a.text) == false && $.isNumeric(b.text) == false) {
var aA = a.text
var bA = b.text;
return aA > bA ? 1 : -1;
} else if ($.isNumeric(a.text) == false) { // A is not an Int
return 1; // to make alphanumeric sort first return -1 here
} else if ($.isNumeric(b.text) == false) { // B is not an Int
return -1; // to make alphanumeric sort first return 1 here
} else {
return AInt < BInt ? 1 : -1;
}
});
This works fine for a well mixed array.:)
Thank you.
edited Jul 12 '16 at 10:00
varit05
1,640715
1,640715
answered Jul 12 '16 at 9:38
SeemaSeema
1
1
add a comment |
add a comment |
alphaNumericCompare(a, b) {
let ax = , bx = ;
a.replace(/(d+)|(D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || '']) });
b.replace(/(d+)|(D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || '']) });
while (ax.length && bx.length) {
let an = ax.shift();
let bn = bx.shift();
let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
}
add a comment |
alphaNumericCompare(a, b) {
let ax = , bx = ;
a.replace(/(d+)|(D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || '']) });
b.replace(/(d+)|(D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || '']) });
while (ax.length && bx.length) {
let an = ax.shift();
let bn = bx.shift();
let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
}
add a comment |
alphaNumericCompare(a, b) {
let ax = , bx = ;
a.replace(/(d+)|(D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || '']) });
b.replace(/(d+)|(D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || '']) });
while (ax.length && bx.length) {
let an = ax.shift();
let bn = bx.shift();
let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
}
alphaNumericCompare(a, b) {
let ax = , bx = ;
a.replace(/(d+)|(D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || '']) });
b.replace(/(d+)|(D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || '']) });
while (ax.length && bx.length) {
let an = ax.shift();
let bn = bx.shift();
let nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if (nn) {
return nn;
}
}
return ax.length - bx.length;
}
edited Feb 7 '18 at 5:47
Hexfire
3,34081731
3,34081731
answered Feb 7 '18 at 5:00
hitesh kaushikhitesh kaushik
112
112
add a comment |
add a comment |
Here is an ES6 Typescript upgrade to this answer.
export function SortAlphaNum(a: string, b: string) {
const reA = /[^a-zA-Z]/g;
const reN = /[^0-9]/g;
const aA = a.replace(reA, "");
const bA = b.replace(reA, "");
if (aA === bA) {
const aN = parseInt(a.replace(reN, ""), 10);
const bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
add a comment |
Here is an ES6 Typescript upgrade to this answer.
export function SortAlphaNum(a: string, b: string) {
const reA = /[^a-zA-Z]/g;
const reN = /[^0-9]/g;
const aA = a.replace(reA, "");
const bA = b.replace(reA, "");
if (aA === bA) {
const aN = parseInt(a.replace(reN, ""), 10);
const bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
add a comment |
Here is an ES6 Typescript upgrade to this answer.
export function SortAlphaNum(a: string, b: string) {
const reA = /[^a-zA-Z]/g;
const reN = /[^0-9]/g;
const aA = a.replace(reA, "");
const bA = b.replace(reA, "");
if (aA === bA) {
const aN = parseInt(a.replace(reN, ""), 10);
const bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
Here is an ES6 Typescript upgrade to this answer.
export function SortAlphaNum(a: string, b: string) {
const reA = /[^a-zA-Z]/g;
const reN = /[^0-9]/g;
const aA = a.replace(reA, "");
const bA = b.replace(reA, "");
if (aA === bA) {
const aN = parseInt(a.replace(reN, ""), 10);
const bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
answered Aug 14 '18 at 20:04
Devin PrejeanDevin Prejean
465310
465310
add a comment |
add a comment |
A simple way to do this is use the localeCompare() method of JavaScript
https://www.w3schools.com/jsref/jsref_localecompare.asp
Example:
export const sortAlphaNumeric = (a, b) => {
// convert to strings and force lowercase
a = typeof a === 'string' ? a.toLowerCase() : a.toString();
b = typeof b === 'string' ? b.toLowerCase() : b.toString();
return a.localeCompare(b);
};
Expected behavior:
1000X Radonius Maximus
10X Radonius
200X Radonius
20X Radonius
20X Radonius Prime
30X Radonius
40X Radonius
Allegia 50 Clasteron
Allegia 500 Clasteron
Allegia 50B Clasteron
Allegia 51 Clasteron
Allegia 6R Clasteron
Alpha 100
Alpha 2
Alpha 200
Alpha 2A
Alpha 2A-8000
Alpha 2A-900
Callisto Morphamax
Callisto Morphamax 500
Callisto Morphamax 5000
Callisto Morphamax 600
Callisto Morphamax 6000 SE
Callisto Morphamax 6000 SE2
Callisto Morphamax 700
Callisto Morphamax 7000
Xiph Xlater 10000
Xiph Xlater 2000
Xiph Xlater 300
Xiph Xlater 40
Xiph Xlater 5
Xiph Xlater 50
Xiph Xlater 500
Xiph Xlater 5000
Xiph Xlater 58
add a comment |
A simple way to do this is use the localeCompare() method of JavaScript
https://www.w3schools.com/jsref/jsref_localecompare.asp
Example:
export const sortAlphaNumeric = (a, b) => {
// convert to strings and force lowercase
a = typeof a === 'string' ? a.toLowerCase() : a.toString();
b = typeof b === 'string' ? b.toLowerCase() : b.toString();
return a.localeCompare(b);
};
Expected behavior:
1000X Radonius Maximus
10X Radonius
200X Radonius
20X Radonius
20X Radonius Prime
30X Radonius
40X Radonius
Allegia 50 Clasteron
Allegia 500 Clasteron
Allegia 50B Clasteron
Allegia 51 Clasteron
Allegia 6R Clasteron
Alpha 100
Alpha 2
Alpha 200
Alpha 2A
Alpha 2A-8000
Alpha 2A-900
Callisto Morphamax
Callisto Morphamax 500
Callisto Morphamax 5000
Callisto Morphamax 600
Callisto Morphamax 6000 SE
Callisto Morphamax 6000 SE2
Callisto Morphamax 700
Callisto Morphamax 7000
Xiph Xlater 10000
Xiph Xlater 2000
Xiph Xlater 300
Xiph Xlater 40
Xiph Xlater 5
Xiph Xlater 50
Xiph Xlater 500
Xiph Xlater 5000
Xiph Xlater 58
add a comment |
A simple way to do this is use the localeCompare() method of JavaScript
https://www.w3schools.com/jsref/jsref_localecompare.asp
Example:
export const sortAlphaNumeric = (a, b) => {
// convert to strings and force lowercase
a = typeof a === 'string' ? a.toLowerCase() : a.toString();
b = typeof b === 'string' ? b.toLowerCase() : b.toString();
return a.localeCompare(b);
};
Expected behavior:
1000X Radonius Maximus
10X Radonius
200X Radonius
20X Radonius
20X Radonius Prime
30X Radonius
40X Radonius
Allegia 50 Clasteron
Allegia 500 Clasteron
Allegia 50B Clasteron
Allegia 51 Clasteron
Allegia 6R Clasteron
Alpha 100
Alpha 2
Alpha 200
Alpha 2A
Alpha 2A-8000
Alpha 2A-900
Callisto Morphamax
Callisto Morphamax 500
Callisto Morphamax 5000
Callisto Morphamax 600
Callisto Morphamax 6000 SE
Callisto Morphamax 6000 SE2
Callisto Morphamax 700
Callisto Morphamax 7000
Xiph Xlater 10000
Xiph Xlater 2000
Xiph Xlater 300
Xiph Xlater 40
Xiph Xlater 5
Xiph Xlater 50
Xiph Xlater 500
Xiph Xlater 5000
Xiph Xlater 58
A simple way to do this is use the localeCompare() method of JavaScript
https://www.w3schools.com/jsref/jsref_localecompare.asp
Example:
export const sortAlphaNumeric = (a, b) => {
// convert to strings and force lowercase
a = typeof a === 'string' ? a.toLowerCase() : a.toString();
b = typeof b === 'string' ? b.toLowerCase() : b.toString();
return a.localeCompare(b);
};
Expected behavior:
1000X Radonius Maximus
10X Radonius
200X Radonius
20X Radonius
20X Radonius Prime
30X Radonius
40X Radonius
Allegia 50 Clasteron
Allegia 500 Clasteron
Allegia 50B Clasteron
Allegia 51 Clasteron
Allegia 6R Clasteron
Alpha 100
Alpha 2
Alpha 200
Alpha 2A
Alpha 2A-8000
Alpha 2A-900
Callisto Morphamax
Callisto Morphamax 500
Callisto Morphamax 5000
Callisto Morphamax 600
Callisto Morphamax 6000 SE
Callisto Morphamax 6000 SE2
Callisto Morphamax 700
Callisto Morphamax 7000
Xiph Xlater 10000
Xiph Xlater 2000
Xiph Xlater 300
Xiph Xlater 40
Xiph Xlater 5
Xiph Xlater 50
Xiph Xlater 500
Xiph Xlater 5000
Xiph Xlater 58
answered Sep 28 '18 at 22:10
Mitali BhokareMitali Bhokare
66118
66118
add a comment |
add a comment |
You can use Intl.Collator
It has performance benefits over localeCompare
Read here
Browser comparability ( All the browser supports it )
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
add a comment |
You can use Intl.Collator
It has performance benefits over localeCompare
Read here
Browser comparability ( All the browser supports it )
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
add a comment |
You can use Intl.Collator
It has performance benefits over localeCompare
Read here
Browser comparability ( All the browser supports it )
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
You can use Intl.Collator
It has performance benefits over localeCompare
Read here
Browser comparability ( All the browser supports it )
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
let arr = ["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"]
let op = arr.sort(new Intl.Collator('en',{numeric:true, sensitivity:'accent'}).compare)
console.log(op)
answered Jan 29 at 18:11
Code ManiacCode Maniac
5,8121224
5,8121224
add a comment |
add a comment |
function sortAlphaNum(a, b) {
var smlla = a.toLowerCase();
var smllb = b.toLowerCase();
var result = smlla > smllb ? 1 : -1;
return result;
}
1
This is wrong. Try comparingA10
toA2
. This will sortA10
beforeA2
, butA2
should be sorted beforeA10
.
– cpburnz
Jul 14 '15 at 0:53
add a comment |
function sortAlphaNum(a, b) {
var smlla = a.toLowerCase();
var smllb = b.toLowerCase();
var result = smlla > smllb ? 1 : -1;
return result;
}
1
This is wrong. Try comparingA10
toA2
. This will sortA10
beforeA2
, butA2
should be sorted beforeA10
.
– cpburnz
Jul 14 '15 at 0:53
add a comment |
function sortAlphaNum(a, b) {
var smlla = a.toLowerCase();
var smllb = b.toLowerCase();
var result = smlla > smllb ? 1 : -1;
return result;
}
function sortAlphaNum(a, b) {
var smlla = a.toLowerCase();
var smllb = b.toLowerCase();
var result = smlla > smllb ? 1 : -1;
return result;
}
answered Jul 14 '15 at 0:27
ClayClay
1
1
1
This is wrong. Try comparingA10
toA2
. This will sortA10
beforeA2
, butA2
should be sorted beforeA10
.
– cpburnz
Jul 14 '15 at 0:53
add a comment |
1
This is wrong. Try comparingA10
toA2
. This will sortA10
beforeA2
, butA2
should be sorted beforeA10
.
– cpburnz
Jul 14 '15 at 0:53
1
1
This is wrong. Try comparing
A10
to A2
. This will sort A10
before A2
, but A2
should be sorted before A10
.– cpburnz
Jul 14 '15 at 0:53
This is wrong. Try comparing
A10
to A2
. This will sort A10
before A2
, but A2
should be sorted before A10
.– cpburnz
Jul 14 '15 at 0:53
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4340227%2fsort-mixed-alpha-numeric-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Are the numerical values always at the end of the string?
– Orbling
Dec 2 '10 at 21:47
1
Possible duplicate of How to sort strings in JavaScript
– feeela
Aug 28 '18 at 11:35