In this blog post you are going to learn 6 easy ways to perform JavaScript List Comprehension using built-in JS methods. By the end of this guide, you will be able to use list comprehension in JavaScript as in Python.
What is List Comprehension?
List comprehension is a powerful method to create new arrays from existing arrays. It allows you to generate a new array by applying an expression to each iterable item of an existing dataset. This coding technique is incredibly concise and effective, which makes it a popular choice amongst programmers and web developers.
Many programming languages like Python offer built-in list comprehension, but unfortunately JavaScript doesn’t. Although there is no direct way to perform JavaScript list comprehension, we can achieve similar results by leveraging on other popular JS array methods. More specifically the map() method, the filter() method and the reduce() method.
Array.prototype.map()
The map() method in JavaScript creates a new array by applying a specified function to every iterable element in the original array. This method takes and applies a callback function to each element, and returns the result of this function in the new array. By applying the map() method, the original array is not modified, but a new one is created. These features make it an alternative way to make JavaScript do list comprehension.
const prices = [10, 8, 9, 5];
const discountedPrices = prices.map(price => price * 0.8);
console.log(discountedPrices); // Output: [8, 6.4, 7.2, 4.5]
JavaScriptArray.prototype.filter()
The filter() function is a JavaScript method that creates a new array with all elements that match the conditions provided in a callback function. The callback function is applied to each iterable element and returns the result in a new array. As in the case of map(), the filter() method does not change the original array but it creates a new one. Through filter(), we can store in a new dataset all the values that meet the desired conditions.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(x => x % 2 === 0); // evens = [2, 4]
console.log(discountedPrices); // Output: [2, 4]
JavaScriptArray.prototype.map() and Array.prototype.filter() combined
In the previous lines we have seen that map() and filter() are two alternative ways to achieve list comprehension. Similar to python, but leveraging on JavaScript built-in methods.
In case the code requires more complex operations, filter() and map() can be combined to perform list comprehension in JavaScript. For instance, the two methods can be called to first filter an array based on specific criteria with filter() and then perform an operation on each iterable that passes the conditions. The result is a new array that does not modify the original dataset.
For instance, we can unlock the power of both Array.prototype.filter() and Array.prototype.map() to discount only the prices for expensive items that are above 100$. Here is how you would do it:
const prices = [50, 200, 150, 80, 120];
const discountedPrices = prices
.filter(price => price >= 100)
.map(price => price * 0.8);
console.log(discountedPrices); // Output: [160, 120, 96]
JavaScriptArray.prototype.reduce()
The reduce() method executes a reducer function on each item of the array, resulting in a single return value. This JS array method becomes very useful when performing complex JavaScript list comprehension, such as finding the maximum value, flattening arrays, or removing duplicates.
// reduce() method to remove duplicates from an array
const numbers = [1, 2, 3, 4, 5, 5, 3, 1];
const uniqueNumbers = numbers.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
// uniqueNumbers = [1, 2, 3, 4, 5]
JavaScriptArray spreading
Array spreading in JavaScript, denoted by the ...
operator, allows programmers to expand arrays into individual elements. It significantly simplifies lengthy tasks such as merging or copying arrays. The array spreading method can also be used to add one array into another.
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers);
console.log(result); // Output: 6
JavaScriptJavaScript List Comprehension with for loop
Another popular way to perform list comprehension in JavaScript is through a for loop. The for loop in JavaScript is used to execute a block of code on each iterable element of an array as long as a specified condition is true. Although this method is less concise than map() or filter(), it can still be applied to achieve similar results.
const numbers = [1, 2, 3, 4, 5];
const squares = [];
for (let i = 0; i < numbers.length; i++) {
squares.push(numbers[i] * numbers[i]);
}
console.log(squares); // Output: [1, 4, 9, 16, 25]
JavaScriptNo, JavaScript does not have built-in list comprehension as Python. However, we can achieve similar results by applying JS array methods like map(), filter(), reduce(), array spreading and for loops.
Use Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), array spreading, or For Loops to perform JS list comprehension.
Bottom Line: JS List Comprehension
Although JavaScript does not provide built-in list comprehension techniques, we can achieve similar results by leveraging on the 3 array methods of Array.prototype.map(), Array.prototype.filter() and Array.prototype.reduce().
Depending on the project requirements, you will need to apply the map() method when wanting to perform an operation on each array element or you will use the filter() function when filtering through a dataset. Combine filter() and map() to first filter an array and then perform a calculation on the items that meet the conditions. The Array.prototype.reduce() method should be reserved for more complex logics such as returning the maximum value. Similar results can also be achieve through simple for loops, but they will make your code longer and less efficient.