The point is that I have this Array of objects.
(5) [{…}, {…}, {…}, {…}, {…}] 0: {id: 143, nombre: "1"} 1: {id: 208, nombre: "10"} 2: {id: 209, nombre: "Madrid"} 3: {id: 144, nombre: "Lugo"} 4: {id: 145, nombre: "3"} 5: {id: 152, nombre: "4"}
I need to order by the attribute, name that can be letters or numbers.
Try following examples like:
users.sort(function (a, b){
return ( b.nombre.toLowerCase().localeCompare(a.nombre.toLowerCase()))
});
But it does not do it correctly, the result should be the following:
(5) [{…}, {…}, {…}, {…}, {…}] 0: {id: 143, nombre: "1"} 1: {id: 208, nombre: "3"} 2: {id: 209, nombre: "4"} 3: {id: 144, nombre: "10"} 4: {id: 145, nombre: "Lugo"} 5: {id: 152, nombre: "Madrid"}
Any ideas?
Thank you
You can use the sort() method together with localeCompare() as you were doing but you must indicate that you can also compare numbers. You do this by using an options object provided by the method, and you must also set the locale, since the results provided by localeCompare() vary from language to language.
How are you?
I propose the following solution, based on the valuable comments to your question and as @davidbug suggests it could be achieved in the following way using:
flatMap
: Returns a flattened version of the array.match con regex:
Gets the occurrences of a regular expression.sort
: Returns an ordered array.filter
: Create a new array with all elements that meet a condition.spreat:
Allows an iterable element to be expanded (concatenation for this solution).NUMBERS: flatMap takes the values with the key it needs, in this case name, and returns the flattened array with just the numbers (numbers in a string) with the condition applied using
match()
. Next, filter "removes" the null values (the text), and finally the array is sorted using sort in ascending order.STRING: The same method is applied, with the difference that match() returns only alphabet (letter in a string) and sort uses
localCompare()
in case of having accent marks in its object.Finally spreat operator returns a new array by concatenating NUMS AND STRING
I hope to contribute, Greetings!