Balasubramanian
Balasubramanian

Reputation: 5520

How to filter array of objects in react native?

I want to filter this data array into state and city array. How can I achieve this using lodash or any other better way rather than for loop and maintaining extra arrays.

data: [
    { id: 1, name: Mike, city: philps, state: New York},
    { id: 2, name: Steve, city: Square, state: Chicago},
    { id: 3, name: Jhon, city: market, state: New York},
    { id: 4, name: philps, city: booket, state: Texas},
    { id: 5, name: smith, city: brookfield, state: Florida},
    { id: 6, name: Broom, city: old street, state: Florida},
]

which user click state, list of state appears.

{state: New York, count: 2},
{state: Texas, count: 1},
{state: Florida, count: 2},
{state: Chicago, count: 1},

When user click particular state, list of cities of that state appears. For ex. when user clicks New York state,

{id:1, name: Mike, city: philps}
{id:3, name: Jhon, city: market}

Upvotes: 21

Views: 164402

Answers (5)

Jasim Khan
Jasim Khan

Reputation: 27

 try this way    
const users = [
{
  name: 'John Doe',
  number: '123-456-7890',
  address: '123 Main Street, City, Country',
},
{
  name: 'Jane Smith',
  number: '987-654-3210',
  address: '456 Oak Avenue, Town, Country',
},
{
  name: 'Alice Johnson',
  number: '555-123-4567',
  address: '789 Elm Road, Village, Country',
},
];

const [searchText, setSearchText] = useState('');
const [filteredUsers, setFilteredUsers] = useState([]);

const handleSearch = text => {
setSearchText(text);
const filteredData = users.filter(user => {
  const searchTextLowerCase = text.toLowerCase();
  return (
    user.name.toLowerCase().includes(searchTextLowerCase) ||
    user.number.includes(searchText) ||
    user.address.toLowerCase().includes(searchTextLowerCase)
  );
 });

 setFilteredUsers(filteredData);
};

   <TextInput
        placeholder="Search Name Number or Address"
        placeholderTextColor={'#666'}
        style={styles.bottomSheetSearchBar}
        onChangeText={handleSearch}
        value={searchText}
      />

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You can do this using native javascript by applying filter method which accepts as parameter a callback provided function.

let data = [ { id: 1, name: 'Mike', city: 'philps', state:'New York'}, { id: 2, name: 'Steve', city: 'Square', state: 'Chicago'}, { id: 3, name: 'Jhon', city: 'market', state: 'New York'}, { id: 4, name: 'philps', city: 'booket', state: 'Texas'}, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida'}, { id: 6, name: 'Broom', city: 'old street', state: 'Florida'}, ]

data = data.filter(function(item){
   return item.state == 'New York';
}).map(function({id, name, city}){
    return {id, name, city};
});
console.log(data);

Another approach is to use arrow functions.

let data = [ { id: 1, name: 'Mike', city: 'philps', state:'New York'}, { id: 2, name: 'Steve', city: 'Square', state: 'Chicago'}, { id: 3, name: 'Jhon', city: 'market', state: 'New York'}, { id: 4, name: 'philps', city: 'booket', state: 'Texas'}, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida'}, { id: 6, name: 'Broom', city: 'old street', state: 'Florida'}, ]

data = data.filter((item) => item.state == 'New York').map(({id, name, city}) => ({id, name, city}));
console.log(data);

Upvotes: 52

Saad Mirza
Saad Mirza

Reputation: 1177

Simply Follow filter function For Example

return data.filter(data => data.state == "New York" && count === 2);

Upvotes: 11

Nina Scholz
Nina Scholz

Reputation: 386654

With lodash, you could use _.filter with an object as _.matches iteratee shorthand for filtering the object with a given key/value pair and

use _.countBy with _.map for getting a count of states.

var data = [{ id: 1, name: 'Mike', city: 'philps', state: 'New York' }, { id: 2, name: 'Steve', city: 'Square', state: 'Chicago' }, { id: 3, name: 'Jhon', city: 'market', state: 'New York' }, { id: 4, name: 'philps', city: 'booket', state: 'Texas' }, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida' }, { id: 6, name: 'Broom', city: 'old street', state: 'Florida' }];

console.log(_.filter(data, { state: 'New York' }));
console.log(_
    .chain(data)
    .countBy('state')
    .map((count, state) => ({ state, count }))
    .value()
);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Upvotes: 13

Vivick
Vivick

Reputation: 4991

This is fairly simple using Array.prototype.filter, Array.prototype.map, Array.prototype.reduce and destructuring:

//filter by particular state
const state = /*the given state*/;
const filtered = data
.filter(e => e.state == state)//filter to only keep elements from the same state
.map(e => {
  const {id, name, city} = e;
  return {id, name, city};
});//only keep the desired data ie id, name and city

//get states array
const states = data
.reduce((acc, elem) => {
  const state_names = acc.map(e => e.state);//get all registered names

  if(state_names.includes(elem.state)){//if it is already there
    const index = acc.find(e => e.state==elem.state);
    acc[index] = {state: acc[index].state, count: acc[index].count+1};//increment it's count
    return acc;
  }else//otherwise
    return [...acc, {state: elem.state, count: 1}];//create it
}, []);

cf this jsfiddle to see it in action.

Upvotes: 7

Related Questions