JSFiddle - React, Tailwind, and code Playground

by Ludwig GUERIN

JavaScript

const 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"},
];

//Filter by particular state
const state = "New York";
const filtered = data
.filter(e => e.state==state)
.map(e =>{
  const {id, name, city} = e;
  return {id, name, city};
});

//list of states with counts
const states = data
.reduce((acc, elem)=>{
  const state_names = acc.map(e => e.state);
  if(state_names.includes(elem.state)){
    const index = acc.findIndex(e => e.state==elem.state);
    acc[index] = {state: acc[index].state, count: acc[index].count+1};
    return acc;
  }else
    return [...acc, {state: elem.state, count:1}];
}, []);

alert(states)
console.log(states)

alert(filtered)
console.log(filtered)