Categories
JavaScript Answers

How to do list comprehensions like Python with JavaScript?

Spread the love

Sometimes, we want to do list comprehensions like Python with JavaScript.

In this article, we’ll look at how to do list comprehensions like Python with JavaScript.

How to do list comprehensions like Python with JavaScript?

To do list comprehensions like Python with JavaScript, we can use the array filter method.

For instance, we write

const string = "1234-5";
const forbidden = "-";

console.log(
  [...string].filter((c) => !forbidden.includes(c)).map((c) => parseInt(c))
);

to call filter with an array with the characters in string to return a new array with the characters that aren’t in the forbidden string.

We call map with a callback to convert each value to an int with parseInt.

Conclusion

To do list comprehensions like Python with JavaScript, we can use the array filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *