Javascript 移除数组中对象中的重复键,并聚合每个状态的计数总数
我有这个对象数组,我想在NY中添加计数,但只打印一次NY的状态,如何删除重复的键而不是if语句中的核心“NY” 输入 输出 州计数:NJ:100Javascript 移除数组中对象中的重复键,并聚合每个状态的计数总数,javascript,algorithm,Javascript,Algorithm,我有这个对象数组,我想在NY中添加计数,但只打印一次NY的状态,如何删除重复的键而不是if语句中的核心“NY” 输入 输出 州计数:NJ:100 州计数:NY:200 状态计数:CA:100 我的做法: cityPopulation.forEach(state => { if (state.state === 'NY') { state.count += state.count } console.log(`Count for stat
州计数:NY:200
状态计数:CA:100
我的做法:
cityPopulation.forEach(state => {
if (state.state === 'NY') {
state.count += state.count
}
console.log(`Count for state: ${state.state}: ${state.count}`)
}
)
你可以这样做
const cityPopulation=[{州:'NJ',市:'Jersey',计数:100},{州:'NY',市:'NYC',计数:100},{州:'CA',市:'SFO',计数:100},{州:'NY',市:'Albany',计数:100};
let res=对象.值(城市人口.减少((acc,项目)=>{
如果(根据[项目状态]){
acc[item.state].count=acc[item.state].count+item.count
}否则{
acc[物料状态]=物料
}
返回acc;
}, {}))
console.log(res)
尝试此对象的解构
const城市人口=[
{州:'NJ',市:'Jersey',计数:100},
{州:'NY',市:'NYC',计数:100},
{州:'CA',市:'SFO',计数:100},
{州:'纽约',市:'奥尔巴尼',计数:100},];
让结果={};
for(城市人口的常数键){
结果={
…结果,
[key.state]:结果[key.state]?+result[key.state]++[key.count]:key.count,
};
}
for(结果中的常量状态){
log(`countforstate:${state}:${result[state]}`);
}
将lodash库用作:
const城市人口=[
{州:'NJ',市:'Jersey',计数:100},
{州:'NY',市:'NYC',计数:100},
{州:'CA',市:'SFO',计数:100},
{州:'纽约',市:'奥尔巴尼',计数:100}];
让groupByState=u.groupBy(cityPopulation,item=>item.state);
_.forEach(groupByState,(item,key)=>console.log(key,sumBy(item,'count'))代码>
超级简单只需几行代码即可完成:
尝试使用数组reduce
方法
cityPopulation.forEach(state => {
if (state.state === 'NY') {
state.count += state.count
}
console.log(`Count for state: ${state.state}: ${state.count}`)
}
)
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]}`);
}