删除数组内对象中的重复键,并聚合每个状态 Javascript 的计数总数



我有这个对象数组,我想在 NY 中添加计数,但只打印一次 NY 的状态,如何删除重复的键而不是 if 语句中的硬核"NY"?

输入

const cityPopulation = [
{ state: 'NJ', city: 'Jersey', count: 100 },
{ state: 'NY', city: 'NYC', count: 100 },
{ state: 'CA', city: 'SFO', count: 100 },
{ state: 'NY', city: 'Albany', count: 100 },]

输出

州计数:新泽西州:100 州计数:纽约:200 州计数:加利福尼亚州:100


我的方法:


cityPopulation.forEach(state => {
if (state.state === 'NY') {
state.count += state.count
}
console.log(`Count for state: ${state.state}: ${state.count}`)
}
)

你可以用Array#reduce

const cityPopulation = [ { state: 'NJ', city: 'Jersey', count: 100 }, { state: 'NY', city: 'NYC', count: 100 }, { state: 'CA', city: 'SFO', count: 100 }, { state: 'NY', city: 'Albany', count: 100 },];
let res = Object.values(cityPopulation.reduce((acc, item) => {
if (acc[item.state]) {
acc[item.state].count = acc[item.state].count + item.count
} else {
acc[item.state] = item
}
return acc;
}, {}))
console.log(res)

尝试这个对象解构。

const cityPopulation = [
{ state: 'NJ', city: 'Jersey', count: 100 },
{ state: 'NY', city: 'NYC', count: 100 },
{ state: 'CA', city: 'SFO', count: 100 },
{ state: 'NY', city: 'Albany', count: 100 },];
let result = {};
for (const key of cityPopulation) {
result = {
...result,
[key.state]: result[key.state] ? +result[key.state] + +[key.count] : key.count,
};
}
for(const state in result) {
console.log(`Count for state: ${state}: ${result[state]}`);
}

使用 lodash 库作为:

const cityPopulation = [
{ state: 'NJ', city: 'Jersey', count: 100 },
{ state: 'NY', city: 'NYC', count: 100 },
{ state: 'CA', city: 'SFO', count: 100 },
{ state: 'NY', city: 'Albany', count: 100 }];
let groupByState = _.groupBy(cityPopulation, item=>item.state);
_.forEach(groupByState, (item, key) => console.log(key, _.sumBy(item, 'count')));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

超级简单,你可以用几行代码来完成:

const cityPopulation = [
{ state: 'NJ', city: 'Jersey', count: 100 },
{ state: 'NY', city: 'NYC', count: 100 },
{ state: 'CA', city: 'SFO', count: 100 },
{ state: 'NY', city: 'Albany', count: 100 },]
let results = [];
cityPopulation.map(obj => {
if (!results[obj.state]) {
return results[obj.state] = obj.count;
}
results[obj.state] += obj.count * 1
})
for(const state in results) {
console.log(`Count for state: ${state}: ${results[state]}`);
}

最新更新