skip to Main Content

I have array

 const arr = [
    {id: 1, country: 'Austria'},
    {id: 2, country: 'Germany'},
    {id: 3, country: 'Austria'},
  ];

I tried the following the code to filter it.

arry.map((item,idx) => (
   item.country== "Austria"?(
       console.log(item.id)
   )
   :
   null
))

The output is

1 3

,
but I want to get output after whole filter like

1,3

I want only the IDs where country is Austria as given below.

1,3

3

Answers


  1. use reduce function

    const arry = [
        {id: 1, country: 'Austria'},
        {id: 2, country: 'Germany'},
        {id: 3, country: 'Austria'},
      ];
      
       const result = arry.reduce((acc,item,idx) => {
        
              if(item.country == "Austria"){
                 if(idx === 0) acc += item.id
                 else acc += `,${item.id}`
               }
               
               return acc
          
        }, '')
        
        console.log(result)
    Login or Signup to reply.
  2. This is How I Filter

    const arry = [
        {id: 1, country: 'Austria'},
        {id: 2, country: 'Germany'},
        {id: 3, country: 'Austria'},
    ];
    
    const result = arry.filter((item, index) => {
    
          if(item.country == "Austria"){
             return true
           }
           
           else{
            return false
           }
      
    })
    
    console.log(result)
    
    Login or Signup to reply.
  3. One line answer:

    arr.filter(i => i.country == 'Austria')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search