Hidden Javascript Array features

Hidden Javascript Array features

So you think you know everything there is about Javascript arrays, in this article I will present to you the top hidden Javascript array features that you may find handy now or in your future projects you may want to keep these in mind. So with no further ado, here are my list of Top 5 Hidden Javascript Array features.

1. Iterate through an HTMLCollection collection

A HTMLCollection is a special kind of array you would have dealt with if you do something like document.getElementsByClassName() or document.getElementsByTagName() etc. ES6 comes handy with a way to convert these collections into an array we are all fond with. The below snippet will add an awesome class with every element that has a headers class.

JavaScript
1
2
const headers = document.getElementsByClassName('headers');
[...headers].forEach(header => header.classList.add('awesome'));

As you can see, it is very simple syntax without using a for loop or using Array.from()

2. The power of the Map Reduce

The Array.map() and Array.reduce() functions are pretty ordinary but once you combine them and execute them consecutively, you can do some very neat and interesting things. A good example is that you can hack the reduce function a bit and leverage it to efficiently unit test your sort algorithm.

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const fruits = [
{name: 'apple', price: 1.01, store: 'A'},
{name: 'apple', price: 1.32, store: 'B'},
{name: 'apple', price: 1.55, store: 'C'},
{name: 'orange', price: 2.55, store: 'A'}
];
describe('Sort', () => {
it('Should sort by Price (low-high)', () => {
fruits.map(f => f.price).reduce((a, b) => {
expect(a).toBeLessThan(b);
return b;
});
});
});

As you can see, we don’t have to go through the trouble of storing a temporary variable and swapping it around.

The original use of the reduce function is to “accumulate” which means it can take the sum of the current and previous value. But with some creativity we used it to do something completely different and the result is satisfying. I’m pretty sure there are a lot more things you can come up with and probable use cases for them.

3. Array.every(), Array.find() and Array.some()

Probably the most underused Array functions I’ve seen Developers not taking advantage of them. Yes, you can achieve all of this using the traditional filter function, but it’s much cleaner to use these newer methods to do some common branching in your code. They are pretty much self explainatory of what they do, if you would like to know more and what they return, it is linked to the docs for your convenience.

4. Destructuring

Ever wanted to cleanly define functions, but parameters only accept an array and it’s confusing to guess what they are without using object to name them something.

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const str = '3,4';
function findStuff(coordinates) {
let x = coordinates[0];
let y = coordinates[1];
console.log(x, y);
}
findStuff(str.split(','));
// or you can just do this
function findStuff([x, y]) {
console.log(x, y);
}
findStuff(str.split(','));

There are many more neat stuff you can do with object and array destructuring, more information can be found here.

5. Use Lodash or Underscore.js for more complex operations

Anything beyond the native array prototype I tend to use Lodash or Underscore.js, if you haven’t yet to use them already I strongly recommend you to take a look at their comprehensive list of functions and what they can bring to your project. My favorite one is .zipObject, which can zip two arrays and turn them into key-value pairs, similar to how python does it.

JavaScript
1
2
3
4
import _ from 'lodash';
_.zipObject(['a', 'b'], [1, 2]);
// => { 'a': 1, 'b': 2 }

That’s it for now, it’s been some time since I have posted an article. Nevertheless, I really hope that you guys enjoyed reading this and maybe found some of the features to be useful. Until next time, and Happy Easter!