DEV Community

Jen C.
Jen C.

Posted on

JavaScript - Map and filter an array at the same time

Create a new string array by converting elements from a number array, ensuring each converted number is greater than 4.

const arr = [1,2,3,4,5,6,7,8,9];
Enter fullscreen mode Exit fullscreen mode

Results:

console.log(newArr);
Enter fullscreen mode Exit fullscreen mode

Image description

Solution 1: Array.prototype.flatMap()

const newArr = arr.flatMap(ele => (ele> 4)? ele.toString(): []);
Enter fullscreen mode Exit fullscreen mode

Solution 2: use Array.prototype.map() and Array.prototype.filter()

const newArr = arr.filter(ele => ele > 4).map(ele=> ele.toString());
Enter fullscreen mode Exit fullscreen mode

Solution 3:

Reference

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#for_adding_and_removing_items_during_a_map
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site