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];
Results:
console.log(newArr);
Solution 1: Array.prototype.flatMap()
const newArr = arr.flatMap(ele => (ele> 4)? ele.toString(): []);
Solution 2: use Array.prototype.map()
and Array.prototype.filter()
const newArr = arr.filter(ele => ele > 4).map(ele=> ele.toString());
Solution 3:
Reference
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap#for_adding_and_removing_items_during_a_map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Top comments (0)