Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  147] [ 1]  / answers: 1 / hits: 147094  / 7 Years ago, sat, october 21, 2017, 12:00:00

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}

More From » arrays

 Answers
11

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>




[#56165] Wednesday, October 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;