pedro_bb7
pedro_bb7

Reputation: 2091

Insert in an array elements that fulfill condition

Context

class Park extends Place {
    constructor(name, build_year, number_trees, area, tree_density){
        super(name, build_year);
        this.number_tress = number_trees;
        this.area = area;
        this.tree_density = number_trees/area;
    } `

`const park1 = new Park("Jadim botanico", 1958, 30, 30);
 const park2 = new Park("Tangua", 1990, 60, 15);
 const park3 = new Park("Bosque do Papa", 1996, 10000, 300);
 arr_park = [park1, park2, park3];`

Goal

Retrieve all the parks that have more than 1000 trees.

Solution

var bushyPark = arr_park.map(cur => {if(cur.number_tress>1000){return cur.name}}).filter(cur => cur);

Question

Is it possible to do the same thing using ternary operator without filter?

var bushyPark = arr_park.map(cur => (cur.number_tress > 1000) ? cur : ??

Upvotes: 0

Views: 56

Answers (2)

ismnoiet
ismnoiet

Reputation: 4159

You can directly use .filter without .map method, it is unnecessary in this case:

const bushyPark = arr_park.filter(cur => cur.number_tress>1000);
console.log('new array: ', bushyPark);

.map: this method is used to manipulate/change the content of every item in the array.

.filter: this method is used to return only the array items that satisfy a boolean criteria.

Here is a definition for the .filter method for a better understanding:

The filter() method creates an array filled with all array elements that pass a test (provided as a function). Note: filter() does not execute the function for array elements without values. Note: filter() does not change the original array.

Another solution using only .map:

let newNamesArray = [];
arr_park.map(cur => {
  if(cur.number_tress>1000){
   newNamesArray.push(cur.name);
  }
  return cur;
})
console.log('newNamesArray: ', newNamesArray);

Upvotes: 4

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

You can use Array.reduce if you want add some conditions like name, try this

   arr_park.reduce((acc, ele)=> {
     if(ele.number_tress>1000){
      acc.push(ele.name)
    }
    return acc
    }
    ,[])

Upvotes: 1

Related Questions