Sort an array with integer string types in jQuery

I have an array of integers of type string.

var a = ['200','1','40','0','3']; 

Exit

 >>> var a = ['200','1','40','0','3']; console.log(a.sort()); ["0", "1", "200", "3", "40"] 

I will also have an array of mixed type. eg.

 var c = ['200','1','40','apple','orange']; 

Exit

 >>> var c = ['200','1','40','apple','orange']; console.log(c.sort()); ["1", "200", "40", "apple", "orange"] 

====================================================
Integers of type string are not sorted.

+4
source share
5 answers

As others have said, you can write your own comparison function:

 var arr = ["200", "1", "40", "cat", "apple"] arr.sort(function(a,b) { if (isNaN(a) || isNaN(b)) { return a > b ? 1 : -1; } return a - b; }); // ["1", "40", "200", "apple", "cat"] 
+15
source

It should be what you are looking for

 var c = ['200','1','40','cba','abc']; c.sort(function(a, b) { if (isNaN(a) || isNaN(b)) { if (a > b) return 1; else return -1; } return a - b; }); // ["1", "40", "200", "abc", "cba"] 
+5
source

You need to write your own sort function.

 a.sort(function(a,b)) { var intValA = parseInt(a, 10); var intValB = parseInt(b, 10); if (!isNaN(parseInt(a, 10))) && !isNaN(parseInt(b, 10)) { // we have two integers if (intValA > intValB) return 1; else if (intValA < intValB) return 0; return 1; } if (!isNaN(parseInt(a, 10)) && isNaN(parseInt(b, 10))) return 1; if (isNaN(parseInt(a, 10)) && !isNaN(parseInt(b, 10))) return -1; // a and b are not integers if (a > b) return 1; if (a < b) return -1; return 0; }); 
+1
source

Thanks to everyone, although I do not know jQuery very well, but from you guys examples, I summed up the code as follows, which works as per my requirement

for use in firebug

 var data = ['10','2', 'apple', 'c' ,'1', '200', 'a'], temp; temp = data.sort(function(a,b) { var an = +a; var bn = +b; if (!isNaN(an) && !isNaN(bn)) { return an - bn; } return a<b ? -1 : a>b ? 1 : 0; }) ; alert(temp); 
0
source

Most javascript implementations, as far as I know, provide a function that you can pass to provide your own custom sorting.

Mozilla Sort Method

-one
source

Source: https://habr.com/ru/post/1499984/


All Articles