3 ms·
I had some javascript where I wanted to sort a list of list of integers as follows: * Sort each inner list smallest to largest * Sort the list of lists
by CJefferson 11y ago
I had some javascript where I wanted to sort a list of list of integers as follows:
* Sort each inner list smallest to largest
* Sort the list of lists lexicographically
It amazed that (a) how stupid javascript's default sort is, and (b) how none of the famous libraries (underscore/lodash) seem to have even fixed the problem of arrays not being compared element-wise, or provide an easy drop-in replacement.
EDIT: I replaced the word 'lexicographic' with 'element-wise', as I think it might be causing confusion.
- lotsoflumens 11y agoYes - even Typescript, when arrays are given types, doesn't fix it even though it could be done easily. var x : number[] // should compile: x.sort(function(a,b) { return a - b; }) var y : string[] // should compile: y.sort() The reason that this isn't done is due to a misplaced ideology about "typescript is just javascript" - or some similar nonsense. The bigger problem here is that we are using tools that are designed by a committee, and we have almost no hope of getting this fixed.
- xlm1717 11y agoIt can easily be fixed by passing a sorting function...
- CJefferson 11y agoWell, but then I have to write a comparison function for two arrays of integers. It's not that hard to write, but it took me long enough that I wished the language had it built in (should probably look for it in npm.. if there is left-bad, there must be array-order!)
- akavi 11y agoWhat would "lexicographic" comparison of two arrays mean? As in, what's the canonical string conversion, and how should commas be treated in the ordering? (eg, does `[1,2]` come before or after `[12]` ?) Admittedly, "lexicographic" sorting of numbers is pretty wonky too, but at least there's a pretty canonical string representation of a given number. It seems like a pretty idiosyncratic need without an obvious canonical interpretation, so I'm a little surprised by your surprise at there not being standardish library function for it. Edit: Oh, how embarrassing, I misunderstood the linked post (I thought it was about JS lexicographically sorting integers, rather than arrays of integers). Well, I guess my surprise applies to both you and the author of the link.
- CJefferson 11y agoLexicographic ordering of two arrays X and Y is (I think) the standard ordering of arrays. Algorithm something like (pseudocode, ignoring different length arrays): for(i = 0; i < length(X); ++i) { if(X[i] < Y[i]) X is smaller if(X[i] > Y[i]) Y is smaller } arrays are equal! In every programming language I've ever used (other than Javascript), the following is how arrays are ordered (well, except for languages like C, where they are compared by memory location by default) [1,1] < [2,2] < [11,11] < [22,22] Instead Java says [1,1] < [11,11] < [2,2] < [22,22], because it compares the arrays as strings.