Going Functional: Three Tiny Useful Functions - Some, Every, Pluck

Some, Every

Every now and then in your everyday programmer’s life you come across an array and you need to determine something, usually whether all the elements in the array pass a certain test.

You know, something like:

var allPass = true;
for (var i = 0; i < arr.length; ++i) {
 if ( ! passesTest(arr[i])) {
   allPass = false;
   break;
 }
}

Or the mirror image: figure out whether any element in the set passes a test.

Now, the for loop above (or a similar construct for the “any” problem) is not too bad. But hey, it’s still six lines of code. And the purpose is not too clear at first glance. So let’s not reinvent the wheel and just use every:

var allPass = arr.every(function(item) { return passesTest(item); });

or better yet:

var allPass = arr.every(passesTest);

Much nicer, isn’t it? Similar for some, which returns true if any element matches.

Those two functions have been available in the all major browsers for quite a while now. If you’re unlucky enough to have to deal with IE8 or worse, you can use Lo-Dash or Underscore libraries.

Pluck

Pluck is useful when you have an array of objects and you’re only interested in one of their properties. It constructs an array comprising the values of said property. Say you want to know the average height of an NBA player.

var nbaPlayers = [
 {age: 37, name: "Manu Ginóbili", height: 1.98},
 {age: 36, name: "Dirk Nowitzki", height: 2.13},
 //...
];

var averageHeight = avg(_.pluck(nbaPlayers, 'height'));

Well, so much for low variance

Another way to look at that is that pluck is merely shorthand for map. It is, but it’s still very handy. pluck is not a standard JS function but you can find it in any good functional JS library (be it Lo-Dash, Underscore or some other).