Today I Learned

hashrocket A Hashrocket project

Avoid mutating array when sorting

I just ran into a hard to track down bug with code that amounted to this.

> a = [6,5,4,3,2,1]
[ 6, 5, 4, 3, 2, 1 ]
> a.map(function(x) { console.log(x); a.sort()})
6
2
3
4
5
6

Why is the second number 2 and not 5? Oh, because I was sorting the array. In my program I needed to gather some information about the collection as a whole and the sort statement was buried 2 function calls down, and didn't realize the collection was being mutated while it was being iterated.

To avoid this, a best practice might be to copy the array before sorting it, two examples of that would be:

a.concat().sort()

And

a.slice(0).sort()

Same number of characters; choose your favorite.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.