Does JavaScript Support Array/List Comprehension

As of ES2022 or ESNext, JavaScript does not have built-in support for Array comprehension or List comprehension like Python.

However, you can create an array or list comprehension functionality using the “Array.prototype.map()” along with the “Array.prototype.filter()” methods or the “Array.from()” method in JavaScript.

Method 1: Using the Array.prototype.map() along with Array.prototype.filter()

You can create a new array of squares for each even number in an existing array using the “map()” and “filter()” methods.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const evenSquares = numbers.filter(num => num % 2 === 0).map(num => num * num);

console.log(evenSquares);

Output

In this example, we first used the filter() method to create a new array containing only the even numbers, then used the map() method to create another new array with the squares of the even numbers.

Method 2: Using the Array.from()

You can also use “Array.from()” to create a new array from an existing one by providing a mapping function.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const evenSquares = Array
   .from(numbers, num => (num % 2 === 0 ? num * num : undefined))
   .filter(Boolean);

console.log(evenSquares);

Output

In this code, we used the “Array.from()” method to create a new array where even numbers are squared and odd numbers are set to an undefined.

In the next step, we used the filter(Boolean) to remove undefined elements from the resulting array.

Leave a Comment