DEV Community

Matthias Hryniszak
Matthias Hryniszak

Posted on

Extending Array.prototype

I think the Array API is awesome. It's great. In fact, there's little that can't be done with what we have at our disposal. Filtering, mapping, reducing, pushing new items to the array, splitting, accessing individual elements... You name it. It's all there.

The only problem is that they are super generic. For example, if you'd like to get the tail of an array you'd have to rely on splice, which has quite a vague syntax. One that definitely does not say that what you're interested in is the tail.

There are more examples of that and not even that obvious. For example if you'd like to just sort the array you'd need to provide a comparison function. However, in that case you'll get the original table sorted - something you don't necessarily want. If, however, you'd like to get a copy that is sorted then you need to resort to constructs like

[...array].sort((a, b) => ...)
Enter fullscreen mode Exit fullscreen mode

It's not much but if you need to do it many times in the code then it becomes obtrusive and reading that kind of code is difficult. Same thing for calculating min/max/median/average of values stored in the array. It just doesn't look readable.

This is why I have created the array-prototype-functions library. It augments the Array.prototype adding those functions that are commonly used.

For example, there's a [1, 2, 3].sum() function that will, well, return 6. Consequently, there's also a min, max, median and avg functions provided for convenience. min, max and median works also for strings by default comparing items using the localeCompare function.

You might ask what would happen if what you've had in the array are objects and not just values? Well, each of those functions accepts also a field name to extract or (in the extreme cases) a mapping function that should return the value for comparison.

There are also two additional functions that I found very useful and pretty unintuitive to implement: groupBy and uniq. groupBy takes a field name or mapping function and produces an object that has the values as keys and a list of matching objects as values. uniq is kind of self-explanatory: it returns unique values of a given field.

Using the library doesn't mean you have to include all the augmentation functions at once. The library is designed in such a way that you pick and choose what's of interest to you. For example, to just use the sortBy function:

import 'array-prototype-functions/sort-by'
Enter fullscreen mode Exit fullscreen mode

The library provides of course full type information and is itself written in TypeScript.

I hope you'll enjoy using it - I know I am. I wrote those functions so many times previously in so many projects to increase the readability of the code it came to the point where fixing errors is just not practical anymore. Now you and I can pick it off-the-shelf.

Top comments (0)