城市及其国家/地区以以下结构给出:
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 =[];
let sum= 0;
for ( elem of data){
arr.push(elem.country)
}
let uniqueCountries = [...new Set(arr)];
console.log(uniqueCountries.length)
它起作用了。
我的问题是:
是否有可能找到更好的解决方案(例如,不使用新的集合)?
发布于 2019-11-13 14:09:13
Set有一个可以使用的size属性。您还可以通过在set实例化中使用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" }
]
const set = new Set(data.map(o => o.country))
console.log(set.size)
我不知道你为什么不在这里使用集合,但是如果你愿意,你可以使用地图来代替:
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)
发布于 2019-11-13 14:10:15
Set将是一种更干净的方式。您可以使用map()而不是for循环来清理代码。在设置之前,您将使用一个对象并遍历列表并获取国家/地区。
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)
要使您的代码更简洁,请将for循环替换为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
发布于 2019-11-13 14:11:49
您可以使用reduce
方法统计国家/地区:
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);
https://stackoverflow.com/questions/58838921
复制相似问题