You have an array; you want to find an element in the array. What do you do?
Most developers go with the old procedural for loop:
var items = [
{ Name = "Matthew", Id = 1 },
{ Name = "Mark", Id = 2 },
{ Name = "Luke", Id = 3 },
{ Name = "John", Id = 4 }
];
// Find the item with Id === 3
var matchingItem = null;
for (i = 0; i < items.length; i++) {
if (items.Id === 3) {
matchingItem = item;
break;
}
}
// Do something with matchingItem
}
What’s wrong with this?
It’s the classic procedural programming affliction: over-specification. It painfully specifies all the steps the program must take to reach the desired state.
All you want is the item with an Id of 3, but instead you create a new loop variable, increment that variable each loop, use special loop iteration language syntax, index into the array, check if it matches your condition, store the match in a mutable variable.
The how obscures the what.
Thank you sir, may I have another.
This obfuscates the intent of your code via over-specificying pageantry.
It’s also error prone. The above code omitted the var declaration for the loop variable i, (did you catch that?), thus adding it to the global scope (oops!). Developers often forget to break; out of the for loop when a match is found, resulting in superfluous loop iterations at best, unintended behavior at worst.
Can we do better?
How about .filter?
Today’s JavaScript (1.5+) includes the built-in .filter function:
var items = [
{ Name = "Matthew", Id = 1 },
{ Name = "Mark", Id = 2 },
{ Name = "Luke", Id = 3 },
{ Name = "John", Id = 4 }
];
// Find the item with Id === 3
var matchingItem = items.filter(function(item) {
return item.Id === 3;
})[0];
// Do something with matchingItem...
.filter is a higher-order function that returns all elements in the array that match your predicate. The above code calls .filter(…) and then gets the first matching item.
This is better, but still not right.
What’s wrong with this? Like a for loop that forgot to break; out of the loop after finding a match, .filter will iterate over your entire array, even if it already found a match. This will result in superfluous iterations. And if your code doesn’t account for multiple items matching your condition, you’ll get unexpected behavior.
Solution
There’s no way to do this efficiently or succinctly using any of the built-in JavaScript array functions.
Because of this, most developers just do the ugly one, or the inefficient one.
A proper solution would be a function added to the Array prototype chain. In lieu of the browser vendors doing that, we can do it like this:
if (!Array.prototype.first)
{
Array.prototype.first = function(predicate)
{
"use strict";
if (this == null)
throw new TypeError();
if (typeof predicate != "function")
throw new TypeError();
for (var i = 0; i < this.length; i++) {
if (predicate(this[i])) {
return match;
}
}
return null;
}
}
Here, we’ve defined a .first method on the Array prototype. It uses the efficient-but-ugly for loop. But instead of coding up this for loop every time, we can now just call our higher-order function:
var items = [
{ Name = "Matthew", Id = 1 },
{ Name = "Mark", Id = 2 },
{ Name = "Luke", Id = 3 },
{ Name = "John", Id = 4 }
];
// Find the item with Id === 3
var matching = items.first(function(i) { return i.Id === 3 });
// Do something with match...
Much cleaner, syntactically similar to .filter, but without the superfluous iterations.
JavaScript has no lambda syntax (yet), so it’s not as clear as it could be. Ideally, we’d write it more succinct, something like:
var matchingItem = items.first(item => item.Id === 3);
We’ll have to wait for the proposed arrow function syntax for the next version of JavaScript before we can get that succinct.
In the meantime, Array.prototype.first is a nice polyfill with decent syntax, allowing your code to focus on what, rather than how.