Javascript is nice. It has a tiny set of native functions, and allows you to do almost anything you’d like. A quick trick I learned today is how to sort an array of objects rather painlessly. Let’s say you have the following array full of objects:
1 2 3 4 5 6 | |
You want to sort these people by their age. Javascript has a native .sort function for arrays, that either lexically or numerically sorts an array… but that won’t quite cut it for our use case. Luckily, this method also accepts a function as a parameter to help you sort. Documentation at Mozilla Developer Center. Suitable code would look something more like this:
1 2 3 4 5 6 7 8 9 10 11 | |
So you can literally put in any method of comparing first and second that you want and set the return value to be 1 or -1 and the function will sort it appropriately. You could ping two servers and sort by latency, or request a series of recent tweets from an array of Twitter username and sort by most recently posted… The list goes on, but it’s a pretty powerful function beyond face value.