How to filter array of objects in react native?
Asked Answered
H

5

20

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}
Humic answered 21/10, 2017 at 11:56 Comment(1)
Possible duplicate of What is the most efficient method to groupby on a javascript array of objects?Bogie
S
13

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>
Sludgy answered 21/10, 2017 at 12:57 Comment(4)
for states count, its printing out data array as a result.Humic
The output is exactly correct as showing in sinppet. But i'm not getting the same.Humic
For the second console. Getting data as resultHumic
you could add value() to get a rendered result without methods of lodash.Sludgy
F
51

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);
French answered 21/10, 2017 at 12:0 Comment(3)
I have some empty in the array object. How can I remove and need to use the values. Here need to show all except empty. let data = [ { id: , name: '', city: '', state:''},{ 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);Vardon
let data = [ { id: , name: '', city: '', state:''},{ 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);Forbidden
Yall realized this doesn't work in the emulators or in the actual device? I think the question was constructed for this purpose.Labbe
S
13

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>
Sludgy answered 21/10, 2017 at 12:57 Comment(4)
for states count, its printing out data array as a result.Humic
The output is exactly correct as showing in sinppet. But i'm not getting the same.Humic
For the second console. Getting data as resultHumic
you could add value() to get a rendered result without methods of lodash.Sludgy
Z
11

Simply Follow filter function For Example

return data.filter(data => data.state == "New York" && count === 2);
Zymolysis answered 10/8, 2018 at 17:7 Comment(0)
P
7

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.

Precentor answered 21/10, 2017 at 12:25 Comment(0)
T
0
 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}
      />
Taphole answered 7/12, 2023 at 6:31 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Prescribe

© 2022 - 2024 — McMap. All rights reserved.