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 !
The idea here is to create a
Set from our values, and then convert it back to an array (if need be):
Before converting back to an array, keep in mind that
Set itself has some useful tools, such as
has for instance.
Here we update the object that has
id: 3 in the array.
Let’s remove the object that has
id === 3 from our array:
You can use denormalized assignment the other-way around:
With this piece of code we can either merge objects together, or update them by their properties:
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 :)