We need a little more information and code to be able to help you. What would be very helpful is to know:
What language are you using? This looks like it could be on a web page or a desktop app although your snippet of code does indicate JS.
What data populates and creates the rendered list? I would do my sorting on the data before rendering the list.
If this is a web app project, it would be highly beneficial if you can create a JSFiddle, CodePen, ReplIt, or something like that with as much code as you can replicate client side to create this list, so that we can offer the most amount of help possible.
I am using Angular 14.
I wanted to show my string + number array list as it is in material dropdown. but it is not giving proper result. I didn’t apply any sort data list of dropdown.
The snippet @Teller gave you would solve your problem then. You just need to replace your sort function with the sort function he gave you in his reply:
return reportingPeriodList.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
You need to actually show the code you’re using, but if you’re doing what I think you’re doing:
It doesn’t make any difference what framework your using, if you’re sorting numerically you need to sort by number. If you have strings “RP1”, “RP2”, “RP12”, etc, then if you sort by string then it will sort by string (and by character). So in that case, the correct order would be “RP1”, “RP12”, “RP2”, not “RP1”, “RP2”, “RP12”, which is not alphabetic.
But then the error seems to have nothing to do with that: you’re passing value/s of undefined into the sort function, so that’s not sortable (the values are undefined). So you need to show an actual code example
You just quoted a sorting algorithm that won’t work with the data set, assuming it’s in the string form with RP inside. If we assume the data set is in this format ["RP 0", "RP 19", "RP 1"] since we have nothing else to go off of, you’d have to either clean the data set first because you also cannot have any undefined select entries or make the sort function a little more complex to accomodate for null/undefined values. And you couldn’t use a - b for your sorting algorithm since it does not sort numerals inside of strings correctly.
Try to run the a - b sorting on the array with RP strings and you’ll see it’s sorting in unicode order, not numerical:
const list = ["RP0", "RP1", "RP19", "RP2", "RP22", "RP12", "RP3", "RP7"].sort((a, b) => a -b);
console.log(list);
//outputs: ['RP0', 'RP1', 'RP19', 'RP2', 'RP22', 'RP12', 'RP3', 'RP7']