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

Top comments (0)