How to filter array of objects in react native?

Balasubramanian picture Balasubramanian · Oct 21, 2017 · Viewed 66.7k times · Source

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}

Answer

Mihai Alexandru-Ionut picture Mihai Alexandru-Ionut · Oct 21, 2017

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