Array comprehension is creating a list B based on another list A, where each entry of B is the result of a custom operation performed on the items of list A.
Comprehension prevents us from using manual iteration which is error-prone and tedious.
JavaScript(ES5) already has similar built-in map
and filter
functions.
Map & Filter
Best way to understand Array comprehensions is by comparing it with map and filter functions.
Array.prototype.map
This built-in function returns a new array which is the result of applying a callback function.
[1, 2, 3].map(function (i) {
return i * i;
}); // [1, 4, 9]
[100,012,8000].map(String).join('-'); // "100-012-8000"
We could create an array with Number
in-built function.
Array.apply(null, Array(5))
.map(Function.prototype.call.bind(Number)); // [0, 1, 2, 3, 4]
Array.apply(null, {length: 5})
.map(Number.call, Number); // [0, 1, 2, 3, 4]
Array.prototype.filter
This function lets you include
or exclude
some entries of the array based on some certain criteria.
[1,0,2,4,-8,6].filter(function(i) {
return i < 3
}); // [1, 0, 2, -8]
Filters in practice
Practical/real world implementations of filters
can be - find the students who have passed a course.
Array Comprehension in ES6
Part of Firefox but not available in ES5, array comprehensation is now officially a part of ES6.
Easiest way to understand Array Comprehension is by comparing it with map
and filter
.
Let's take the previous map example.
[1, 2, 3].map(function (i) {
return i * i;
}); // [1, 4, 9]
[for(i of [1, 2, 3]) i * i]; // [1, 4, 9]
Here array comprehension uses of
clause to iterate the sequence of the array.
Filtering using array comprehension is straightforward.
[1,0,2,4,-8,6].filter(function(i) {
return i < 3
}); // [1, 0, 2, -8]
[for (i of [1,0,2,4,-8,6]) if(i < 3)];
As you can see, if
operates as the filter" to produce the sequence we need.