Gathering JSON objects with same key value - javascript

I tried to solve the problem on my own but I did not manage to. So I decided to ask for help.
I've got an array of JSON objects like this:
const objArr = [
{
name: 'Andrew',
city: 'London'
},
{
name: 'Edouard',
city: 'Paris'
},
{
name: 'Nathalie',
city: 'London'
},
{
name: 'Patrick',
city: 'London'
},
{
name: 'Mathieu',
city: 'Paris'
}
];
I want to gather objects with same key value - in that case the city key - in a new array to obtain this:
const newObjArr = [
[{
name: 'Andrew',
city: 'London'
},
{
name: 'Nathalie',
city: 'London'
},
{
name: 'Patrick',
city: 'London'
}],
[{
name: 'Edouard',
city: 'Paris'
},
{
name: 'Mathieu',
city: 'Paris'
}]
];

This is a job for .reduce().
const objArr = [
{name: 'Andrew', city: 'London'},
{name: 'Edouard', city: 'Paris'},
{name: 'Nathalie', city: 'London'},
{name: 'Patrick', city: 'London'},
{name: 'Mathieu', city: 'Paris'}
];
// Object of arrays
const result = objArr.reduce((acc, obj) => {
return {...acc, [obj.city]: [...acc[obj.city] || [], obj]}
}, {})
// Array of arrays
const result2 = Object.values(result);
console.log(result2)

Use lodash group by and then add to new array
var objArr = [ { name: 'Andrew', city: 'London' }, { name: 'Edouard', city: 'Paris' }, { name: 'Nathalie', city: 'London' }, { name: 'Patrick', city: 'London' }, { name: 'Mathieu', city: 'Paris' } ]
var grouped = _.mapValues(_.groupBy(objArr, 'city'),
clist => clist.map(city => _.omit(city, 'city')));
var result=[]
for (const [key, value] of Object.entries(grouped)) {
var array=[]
value.forEach(x=>{
array.push({ name: x.name, city:key })
})
result.push(array);
}
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

You can use reduce to group by a field using that field as the key and then use Object.values if you really just want the values:
const objArr = [ { name: 'Andrew', city: 'London' }, { name: 'Edouard', city: 'Paris' }, { name: 'Nathalie', city: 'London' }, { name: 'Patrick', city: 'London' }, { name: 'Mathieu', city: 'Paris' } ];
var groupBy = function(array, k) {
return array.reduce(function(acc, cur) {
(acc[cur[k]] = acc[cur[k]] || []).push(cur);
return acc;
}, {});
};
console.log(Object.values(groupBy(objArr, 'city')));

Related

Why is my condition that checks diff between two arrays of objects wrong?

What is wrong in this if condition. I am getting the wrong result. I need to get equal values in these two objects and diff between them.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
for (let i = 0; i < firstArr.length; i++) {
for (let j = 0; j < secondArr.length; j++) {
if (firstArr[i].name == secondArr[j].name) {
console.log('eq', firstArr[i].city, secondArr[j].city)
}
if (firstArr[i].name != secondArr[j].name) {
console.log('not found in second array', firstArr[i].city)
}
if (secondArr[j].name != firstArr[i].name) {
console.log('not found in first array', secondArr[j].city)
}
}
}
Currently you compare each element of the first array with each element of the second array. You could instead use Array.prototype.some and Array.prototype.every to filter the arrays and to find the intersection resp. difference. Then you can map the objects to the city names.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
function intersect(lhs, rhs) {
return lhs.filter(el => rhs.some(el2 => el.name === el2.name)).map(el => el.city);
}
function diff(lhs, rhs) {
return lhs.filter(el => rhs.every(el2 => el.name !== el2.name)).map(el => el.city);
}
console.log(intersect(firstArr, secondArr));
console.log(diff(firstArr, secondArr));
console.log(diff(secondArr, firstArr));
I loop the first array first and find matches in second array. If there is a match, diff is displayed. If there is no such match, then the correct text is being displayed. An array is built along the way, which is used to simplify the loop on the second array.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
let names = [];
for (let first of firstArr) {
let matches = secondArr.filter((second) => (first.name === second.name));
if (matches.length) {
console.log('eq', first.city, matches[0].city)
} else {
console.log('not found in second array', first.city);
}
names.push(first.name);
}
for (let second of secondArr) {
if (names.indexOf(second.name) === -1) console.log('not found in first array', second.city);
}
Try this:
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
var eq = [], uniqueInFirst = [], uniqueInSecond = [];
for (let i = 0; i < firstArr.length; i++) {
var secondArrCities = Object.values(secondArr).map ((obj) => {return obj.city})
if (secondArrCities.includes(firstArr[i].city)) {
eq.push(firstArr[i].city)
} else {
uniqueInFirst.push(firstArr[i].city)
}
}
for (let i = 0; i < secondArr.length; i++) {
var firstArrCities = Object.values(firstArr).map ((obj) => {return obj.city})
if (!firstArrCities.includes(secondArr[i].city)) {
uniqueInSecond.push(secondArr[i].city)
}
}
console.log(eq)
console.log(uniqueInFirst)
console.log(uniqueInSecond)

Group by array object by object

I have an array of object like that :
[{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
And i would like group by the city, like below:
[{name: 'Peter', age: '22', hobby: 'soccer', cities: ['london', 'Paris']},
{name: 'Mario', age: '30', hobby: 'bike',cities: ['Paris', 'Madrid']},
{name: 'Rick', age: '28', hobby: 'tennis', cities: ['Berlin']}]
I try with this function by, I don't have the good array
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].city;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(arrayPeople[i].city);
}
let arrayGroupBy= [];
for (let groupName in groups) {
arrayGroupBy.push({ ...arrayPeople, cities: groups[groupName] });
}
How I can make my group by ?
Thank for your help.
You can use Array.reduce to process your input array, using the name, age and hobby as a key to create a grouping object, and adding the city for each key to an array in that object. You can then use Object.values to grab just the values from the grouping object into an array:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { city, ...rest }) => {
let key = Object.values(rest).join('#');
c[key] = c[key] || { ...rest, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note the above code is dependent on the properties in the objects being in the same order in each object (in the sample data, name, age, hobby). If this might not be the case, you will need to create the key using the named properties instead, for example:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ age: '30', hobby: 'bike', name: 'Mario', city: 'Paris' },
{ name: 'Peter', hobby: 'soccer', city: 'Paris', age: '22' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { name, age, hobby, city}) => {
let key = `${name}#${age}#${hobby}`;
c[key] = c[key] || { name, age, hobby, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note also that all the above code is dependent on choosing a delimiter (I've used #) that will not occur in the name or hobby values. If there is no suitable delimiter character, then it is safer to use something like JSON.stringify to produce the key value e.g. for the second code block you would use:
let key = JSON.stringify([name, age, hobby]);
Your approach is pretty near to the correct solution. You are grouping persons by city. You have to turn around and group cities by person
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].name;
if (!groups[groupName]) {
groups[groupName] = {name: arrayPeople[i].name, age: arrayPeople[i].age, hobby: arrayPeople[i].hobby, cities: []};
}
groups[groupName].cities.push(arrayPeople[i].city);
}
console.log(Object.values(groups));
This is TypeScript so I'd probably come up with the type corresponding to the final array elements: that is, remove the city property and add a cities property:
type PersonCities = Omit<typeof arrayPeople[number], "city"> & { cities: string[] };
Then you want to put all your objects into a dictionary keyed by whatever you want the grouping condition to be (converted into a string):
const peopleCities: Record<string, PersonCities> = {};
for (let p of arrayPeople) {
const { city, ...person } = p;
const groupByKey = JSON.stringify([person.name, person.hobby, person.age]);
if (!(groupByKey in peopleCities)) {
peopleCities[groupByKey] = { ...person, cities: [] };
}
peopleCities[groupByKey].cities.push(city);
}
const arrayPeopleCities = Object.values(peopleCities);
Here we're making the grouping key a JSON string of the name, hobby, and age properties in an array. And some object rest/spread syntax to copy people properties around without too much redundancy.
Playground link to code

Count the number of countries . (This task is about multidimensional arrays and objects in JavaScript.)

The cities and their countries are given in the following structure:
let data = [
{
country: 'Serbia',
city: 'Belgrad',
},
{
country: 'Ukraine',
city: 'Kiev',
},
{
country: 'Russia',
city: 'Moscow',
},
{
country: 'Russia',
city: 'Sant-Peterborough',
},
{
country: 'Ukraine',
city: 'Lvov',
},
{
country: 'China',
city: 'Beijing',
},
{
country: 'Poland',
city: 'Cracow',
},
];
My solution is :
let arr =[];
let sum= 0;
for ( elem of data){
arr.push(elem.country)
}
let uniqueCountries = [...new Set(arr)];
console.log(uniqueCountries.length)
It works.
My question:
Is it possible to find better solution( not using new Set for example)?
Set has a size property you can use.
You can also simplify your code by using map inside the set instantiation, like so:
let data = [
{ country: "Serbia", city: "Belgrad" },
{ country: "Ukraine", city: "Kiev" },
{ country: "Russia", city: "Moscow" },
{ country: "Russia", city: "Sant-Peterborough" },
{ country: "Ukraine", city: "Lvov" },
{ country: "China", city: "Beijing" },
{ country: "Poland", city: "Cracow" }
]
const set = new Set(data.map(o => o.country))
console.log(set.size)
I'm not sure why you wouldn't use a set here, but if you wanted, you could use a map instead:
let data = [
{ country: "Serbia", city: "Belgrad" },
{ country: "Ukraine", city: "Kiev" },
{ country: "Russia", city: "Moscow" },
{ country: "Russia", city: "Sant-Peterborough" },
{ country: "Ukraine", city: "Lvov" },
{ country: "China", city: "Beijing" },
{ country: "Poland", city: "Cracow" }
];
const map = data.reduce((a, o) => (a[o.country] = 0, a), {})
console.log(Object.keys(map).length)
You can count countries using reduce method:
let data = [
{
country: 'Serbia', city: 'Belgrad',
},
{
country: 'Ukraine', city: 'Kiev',
},
{
country: 'Russia', city: 'Moscow',
},
{
country: 'Russia', city: 'Sant-Peterborough',
},
{
country: 'Ukraine', city: 'Lvov',
},
{
country: 'China', city: 'Beijing',
},
{
country: 'Poland', city: 'Cracow',
},
];
const result = data.reduce((a, {country, city}) =>{
a[country] = a[country] || {count: 0};
a[country].count += 1;
return a;
}, {})
console.log(result);
Set would be a cleaner way of doing it. You could clean up your code using map() instead of the for loop. Before set, you would use an object and loop over the list and get the countries.
let data = [
{ country: 'Serbia', city: 'Belgrad', },
{ country: 'Ukraine', city: 'Kiev', },
{ country: 'Russia', city: 'Moscow', },
{ country: 'Russia', city: 'Sant-Peterborough', },
{ country: 'Ukraine', city: 'Lvov', },
{ country: 'China', city: 'Beijing', },
{ country: 'Poland', city: 'Cracow', },
];
var countries = Object.keys(data.reduce((o, { country }) => o[country] = true && o, {}))
console.log(countries.length)
to make your code cleaner, replace your for loop with map()
let data = [
{ country: 'Serbia', city: 'Belgrad', },
{ country: 'Ukraine', city: 'Kiev', },
{ country: 'Russia', city: 'Moscow', },
{ country: 'Russia', city: 'Sant-Peterborough', },
{ country: 'Ukraine', city: 'Lvov', },
{ country: 'China', city: 'Beijing', },
{ country: 'Poland', city: 'Cracow', },
];
let arr = data.map(o => o.country) // replaces your for loop
const mySet = new Set(arr)
console.log(mySet.size) . // no need to make an array to get length

Concating two arrays into one

I am looking to combine these two arrays into a single one. I want any id information that is the same to be filtered so that it only appears once, making it a simple list of name, age, occupation, and address.
I have tried simply concating the info, using splice, using filter... but I just cant seem to get the right answer.
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}]
I always end up with a single list after the concat, but I cant find out how to filter the same info.
Sounds like you need to merge each item of each array together - and that they're both in the same order, in which case you could do:
const newList = []
a.forEach((item, index) => {
newList.push({
...item,
...b[index]
})
})
console.log(newList)
You can make an object from first array a whole keys will be id of each object. Then use map() on b and return object having all props.
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}]
let obj = a.reduce((ac,a) => (ac[a.id] = a,ac),{});
let res = b.map(x => ({...x,...obj[x.id]}));
console.log(res)
The following will reconstruct the array in the same order as a but the function doesn't depend on b being in the same order.
var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];
let res = a.reduce((a,c) => {a.push({...c, ...b.find(v => v.id == c.id)}); return a;},[])
console.log(res)
And as a more performant solution, that instead of using find for every look-up uses a map-like object for our second array so we just have to insert from it for our result via O(1) look-ups.
So instead of O(n²) we now have O(n):
var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];
let tmp = b.reduce((a,c) => {a[c.id] = c; return a},{}),
res = a.reduce((a,c) => {a.push({...c, ...tmp[c.id]}); return a;},[]);
console.log(res)
If the id is the key to compare,
const concatListById = (base, target) => base.reduce((acc, c) => {
const matched = target.find(e => e.id === c.id);
let el = c;
if (matched) el = { ...matched, ...c };
acc.push(el);
return acc;
}, []);
console.log(concatListById(a, b));
If there is an assumption that id sequence of each array is the same,
const justMergeArray = (base, target) =>
base.map((e, idx) => ({ ...e, ...target[idx] }));
console.log(justMergeArray(a, b));
You can use reduce and compare if id match just push into same object and add this to an array
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}
]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}
]
const res = a.reduce((all, acc, index) => {
if (acc.id === b[index].id) {
all.push({
...acc,
...b[index]
});
}
return all;
}, []);
console.log(res);
Try this:
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}];
const newA = a.reduce((acc, ele) => (acc[ele.id] = ele, ele),{});
const result = b.map(ele=> ({...newA[ele.id],...ele}));
console.log(result);

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}
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);
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>
Simply Follow filter function
For Example
return data.filter(data => data.state == "New York" && count === 2);
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.

Categories

Resources