Sorting in JavaScript, without writing new code

In a lot of programming puzzles / tests you need to sort an array.

You may be all happy to find that JavaScript has a sort() function...

Only to find that it only works on strings.
The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
That's right... it sorts the elements of an array of numbers by converting them to string first.

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
Oh, no! What are we to do if we want it in numeric order? Should we implement bubble sort?

Heck no!

If you keep reading the examples, you'll see the solution quick enough... You need to supply your own compare function, and it's extremely simple.
const array1 = [1, 30, 4, 21, 100000];
array1.sort(function(a,b) {return a-b}) 
console.log(array1);
// expected output: Array [1, 4, 21, 30, 100000]
);
That's right, that's all it takes. If you want to be fancy you can write it ES6 style with a fat arrow function:
array1.sort((a,b) => a-b);
But the result is the same. And that's all you need to sort it by numeric values.

You can easily convert this to sort things your way, from objects or other stuff.

Just keep in mind that while convenient, it is either QuickSort or HeapSort, depending on the browser's JavaScript engine. You can't control that.

It should be fine for a few hundred items. Don't expect it to work well for a few hundred THOUSAND items though.




Comments

Popular posts from this blog

Yet another take on recursion

Problem Solving for Programmers: a Neglected Topic?

How to Solve a Problem, with Examples