Basic javascript algorithms toolbox: starter kit

TL;DR: Here’s a list of javascript quick-to-write algos that are often useful.

Coming from a ruby background, I experienced quite some frustration while learning javascript. A lot of basic methods, like for instance merge,flatten or uniq seemed to be missing in my eyes.

Then I discovered lodash and it was cool… Until I found out that you had to look very closely when running any update, at the risk of breaking things in very improbable ways (of course it happened; I let you imagine what a pleasure it is to debug your code after lodash changed a method that now does almost, but not quite, entirely unlike what it used to do. Bonus points if you didn’t even realise that lodash was updated in the first place).

Few years later, things looks easier thanks to new ES6 standards and I seldomly use lodash or any other libraries for basic algorithms. Here’s a non-exhaustive of what I frequently come across when writing code.

Disclaimer: I don’t pretend to beat lodash on efficiency or algorithm complexity. Besides, lodash is surely an awesome project. The following examples are just simple, easy-to-write pieces of code that work quickly for simple enough cases; we don’t always need the big guns.

Oh, and also, all of the following code respect immutability principles. We never mutates the initial object, but rather return a new object that have the desired properties.

Hope it can also help you !

Uniq Array

The idea here is to create a Set from our values, and then convert it back to an array (if need be):

unify an array, two ways are possible

Before converting back to an array, keep in mind that Set itself has some useful tools, such as size or has for instance.

Update an array object by property

Here we update the object that has id: 3 in the array.

Of course, the “initial” const is remained untouched

Remove an object from array by property

Let’s remove the object that has id === 3 from our array:

Again, initial stays untouched.

Remove a key from an object

You can use denormalized assignment the other-way around:

Merge an array of objects together

With this piece of code we can either merge objects together, or update them by their properties:

reduce and spread operators work really nicely together

Flatten

on-level flattening of an array

FromPairs

I like [key, value] denormalized assignment a lot :)

Subtract two Sets

Less frequent but still useful

Conclusion

All-right, this is all for now. Don’t hesitate to send me more examples, or even to ask for new ones if you feel like I forgot some useful algos !
I might very well update this list as it goes on :)

More by Aurélien Hervé

Topics of interest

More Related Stories