I am trying to sort an object of strings, which would work with the normal sort function, but I am not able to get it working as the strings start with a number:
e.g.:
{ value: "10 items", value: "5 items", value: "100 items", value: "20 items" }
I want to make it ascending, so it becomes:
5 items
10 items
20 items
100 items
I’ve been trying to use:
data.sort((a, b) => a > b ? 1 : -1).map((a) => { return a;}
But that still shows it as:
10 items
100 items
20 items
5 items
4
Answers
You need to compare the first parts of your strings numerically, so we split them, get the first element, convert them to int and then we can compare it. See below:
Note that I have reinterpreted your input, since the one you have given was obviously wrong, as repeating the same key inside an object (
value
) in this case is invalid.You can extract the numbers with
s.slice(0, s.indexOf(' ')
and compare them:If you want to speed up you could compare lengths of the numbers first and then compare them char-by-char if the length is equal:
As @somethinghere mentioned in the comment you can use
localeCompare
to sort numerical datasort
arrays … the OP wants tosort
all of an object’s values.localeCompare
does support numeric comparisonAnd in case the OP wanted to sort an array of equally structured object items, the above solution slightly changes too …