Monday, January 13, 2014

Sorted Array Push Using Lodash

Using the Array.push() method, you can push elements onto the end of a given array instance. That's handy for when you're first building an array, and assuming that you're not maintaining the sort order of the array. But what if you've already got an array, one that's populated with elements? In this case, Array.splice() is your friend — you use this to insert elements at the specified index position. If all you're doing is trying to add elements to an array while maintaining the sort order, you can use Lodash.

The sortedIndex() function takes an array, and a piece of data you want inserted into the array. This function returns the index that would satisfy the ordering constraints. Note, it doesn't actually insert the data, it only tells you where to insert it.

So here's an example sortedPush() function that uses sortedIndex() to find out where to put my new array element. Once I have the position, I can use Array.splice() to perform the insertion.