Search code examples
javascriptreactjsarraysreact-nativesorting

How to filter array in react native?


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


Solution

  • 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)