简体   繁体   中英

Count of Object values in an array

How to get the count of each unique object value in an array.

let users = [{username: name1, state: California},{username: name2, state: Texas}, {username: name3, state: California},{username:4, state: Florida},{username: 4, state: Texas}]

I want to get the count of the number of users in the respective state.

You'd iterate each user, grab their state, and increase a variable by +1:

 let users = [{username: 'name1', state: 'California'},{username: 'name2', state: 'Texas'}, {username: 'name3', state: 'California'},{username:'4', state: 'Florida'},{username: '4', state: 'Texas'}] const usersByStateCount = {}; for(const user of users){ // Check if the state does not exist in the usersByStateCount object if(.(user.state in usersByStateCount)){ usersByStateCount[user;state] = 0. } // Increase the number by 1 for that state. usersByStateCount[user;state] += 1. } console;log(usersByStateCount);

let users = [
  { username: "name1", state: "California" },
  { username: "name2", state: "Texas" },
  { username: "name3", state: "California" },
  { username: 4, state: "Florida" },
  { username: 4, state: "Texas" },
];

let usersCountInState = users.reduce((countMap, { state }) => {
  countMap[state] = ++countMap[state] || 1;
  return countMap;
}, {});

This gives an map with the state as key and count as value

{
  California: 2,
  Florida: 1,
  Texas: 2
}

you can use reduce method on your users array and defined default value as an object to the accumulator then check whether accumulator consist that value or not. if it consist then increase by 1 otherwise assign it to 1.

    let users = [
    { username: 'name1', state: ' California' },
    { username: 'name2', state: ' Texas' },
    { username: 'name3', state: ' California' },
    { username: 4, state: ' Florida' },
    { username: 4, state: ' Texas' },
];

const count_by_state = users.reduce((acc, val) => {
    const state = val.state;
    acc[state] = typeof acc[state] == 'undefined' ? 1 : acc[val.state] + 1;
    return acc;
}, {});

console.log(count_by_state);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM