I found this code that sorts numeric elements of an array depending on which is the largest number, with javascript
var arr = [ 40, 1, 5, 200 ];
arr.sort(function(a,b){return a - b;}); // [ 1, 5, 40, 200 ]
What I need is the same but with strings, I have a array
that contains questions listed within the same string ie
var preguntas = [{
pregunta:"1 Primera Pregunta",
respuesta:"respuesta a pregunta 1"
},{
pregunta:"22 Una pregunta de Pregunta",
respuesta:"respuesta a pregunta 2"
},{
pregunta: 3" tercera Pregunta",
respuesta:"respuesta a pregunta 3"
}]
when using it sort()
sorts them according to their value unicode
1,22,3
and I need to sort them like this1,3,22
How can I do it?
You can call the localeCompare() method with some options defined between the parameters so that it correctly evaluates the numbers and letters embedded in the strings.
It is clear that you will need to access your question property on each item in the array.
The first parameter of the method is
locale
, for thisen
British English case, some other options can be found hereThe second parameter is an options object, for this case we tell it that numeric collation should be used, so
"1" <"2" <"10"
. the default value is false.Ideally, your data model should have a numeric property with the question number:
Since in this way the ordering method would be much simpler using something like:
But since you have to order it with a string you could do something like this:
For each text string stored in
pregunta
, you get from character 0 to the first space, which is a number. That number is still in a text string, so that's usedparseInt
to convert it to its numeric type.Here the sort method returns several numbers in order to do the sorting correctly, as indicated by MDN .
I found this answer in stackOverflow in English
https://stackoverflow.com/questions/8837454/sort-array-of-objects-by-single-key-with-date-value
What you have is an Array of Objects and because of this it changes your JavaScript a bit
The order that it shows you is by Text Chain and not numerical, if you want to make it numerical, the ideal is that it has the number of the question outside to be able to go through it